Ruby on rails 3 Rails 3嵌套属性和访问关联属性

Ruby on rails 3 Rails 3嵌套属性和访问关联属性,ruby-on-rails-3,associations,nested-attributes,Ruby On Rails 3,Associations,Nested Attributes,我有以下情况: 一种产品可以由不同的供应商以给定的价格出售。 在我的产品表单中,我希望通过复选框和 为所选供应商指定价格 我的模型: product.rb class Product < ActiveRecord::Base belongs_to :price has_many :providers, through: :price accepts_nested_attributes_for :providers, :price end # == Schema Inform

我有以下情况: 一种产品可以由不同的供应商以给定的价格出售。 在我的产品表单中,我希望通过复选框和 为所选供应商指定价格

我的模型:

product.rb

class Product < ActiveRecord::Base
  belongs_to :price
  has_many :providers, through: :price

  accepts_nested_attributes_for :providers, :price
end

# == Schema Information
#
# Table name: products
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  isbn       :integer
#  created_at :datetime        not null
#  updated_at :datetime        not null
class Provider < ActiveRecord::Base
  belongs_to :price
  has_many :products, through: :price
end

# == Schema Information
#
# Table name: providers
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime        not null
#  updated_at :datetime        not null
class Price < ActiveRecord::Base
  belongs_to :product
  belongs_to :provider
end

# == Schema Information
#
# Table name: prices
#
#  id          :integer         not null, primary key
#  value       :decimal(, )
#  created_at  :datetime        not null
#      updated_at  :datetime        not null
#  product_id  :integer
#  provider_id :integer
<%= form_for(@product) do |f| %>
...
<div class="field">
    <% Provider.all.each do |provider| %>
      <%= check_box_tag "product[provider_ids][]", provider.id, @product.provider_ids.include?(provider.id), id: dom_id(provider) %>
          <%= label_tag dom_id(provider), provider.name %>
    <% end %>

    <% f.fields_for :price do |price_form| %>
      <%= price_form.text_field :value %>
    <% end %>
    <br>
</div>
...
你需要改变

<% f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>



将产品类别中的
更改为
中的
所属:price
。对于表中有
attribute\u id
的模型,您应该使用
attribute\u to:attribute
方法。

对不起,这只是一个输入错误。但这并没有造成问题。
can't write unknown attribute `price_id'
<% f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>
<%= f.fields_for :price do |price_form| %>
    <%= price_form.text_field :value %>
<% end %>