У меня есть следующий сценарий: Продукт может продаваться разными поставщиками по заданной цене.В моей форме для продукта я хочу выбрать поставщиков с помощью флажков и назначить цену для выбранных поставщиков.
Моя модель:
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
provider.rb
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
price.rb
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
app / views /products / _form.html.erb
<%= 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>
...
Я ничего не изменил в products_controller.Я попытался получить доступ к атрибуту ассоциации price.value с помощью следующего кода в моей форме.
<%= f.fields_for :price do |price_form| %>
<%= price_form.text_field :value %>
<% end %>
Но рядом с флажками не отображается текстовое поле, и когда я выбираю одного поставщика и отправляю форму, я получаю следующееошибка:
can't write unknown attribute `price_id'