У меня вопрос: Продукт может быть продан различными поставщиками за данную цену. В моей форме для продукта я хочу выбрать поставщиков через флажки, а присваивать цену выбранным поставщикам.Rails 3 Вложенные атрибуты и ассоциация доступа Атрибут
Моя модель:
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
приложение/просмотров/Продукты/_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 не изменится. Я попытался получить доступ к атрибуту attribute price.value через следующий код в моей форме.
<%= f.fields_for :price do |price_form| %>
<%= price_form.text_field :value %>
<% end %>
Но не text_field отображаются рядом флажков и при выборе одного поставщика и отправить форму, я получаю следующее сообщение об ошибке:
can't write unknown attribute `price_id'
К сожалению, это была только опечатка. Но это не вызывает проблемы. – bekite