【问题标题】:rails3 is not adding the 2nd id to my tablerails3 没有将第二个 id 添加到我的表中
【发布时间】:2011-06-16 19:53:50
【问题描述】:

我遇到的问题是 company_id 没有保存到详细信息表中 我知道 company_id 在那里我在添加所有公司详细信息之前使用表单上的 检查它,但由于某种原因,除了 company_id 之外,我保存了其他所有内容


##user.rb
has_one :company

##company.rb
belongs_to :user
has_one :detail

##detail.rb
belongs_to :user

##details controller
 def new
    @detail = Detail.new
    user_id = session[:user_id]
    company_id = params[:id]

  end

  def create     
    @detail = Detail.new(params[:detail])
    @detail.user_id = session[:user_id]
    @detail.company_id = params[:id]
  end

###settings.html.erb
### this is where i make sure that company_id gets pass with the url

  link_to 'New Detail', {:controller => 'details', :action =>'new', :id => company.id }, :class => 'plus'

#####routes
    resources :details
    resources :companies
    resources :users
    resources :sessions

如果您知道更好的方法,我知道这可能看起来不漂亮或不合适,请告诉我...提前致谢。

【问题讨论】:

  • 请发布您的新方法呈现的表单。

标签: ruby-on-rails-3 routing foreign-keys models nested


【解决方案1】:

我立刻注意到了一些事情。您可能需要先修复关联。假设用户拥有一家公司,而一家公司拥有一个详细信息。

##user.rb
has_one :company

##company.rb
belongs_to :user
has_one :detail

##detail.rb
belongs_to :user

应该是:

##user.rb
has_one :company

##company.rb
belongs_to :user
has_one :detail

##detail.rb
belongs_to :company

不过,这取决于您的域要求。我通常会将其设置为:用户 has_many 公司。而且由于细节是与公司 1:1 的,所以我会将所有细节都包含在公司内部。

【讨论】:

  • 我解决了这个问题,但仍然没有在表上添加外键
【解决方案2】:

直到后来我才意识到这一点,但我需要它将值传递给视图上的 from 到 from 像这样

  <% @companies.each do |company| %>
      <%= link_to 'New Detail', {:controller =>'details', :action => 'new', :company_id => company.id},  :class => 'plus' %>
    <% end %>

我需要它来收集来自的价值......就像这样

<%= form_for(:detail, :url =>{:action => 'create', :company_id => @company.id}) do |f| %>
...(values)
<% end %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多