アイテムは、コレクションからcollection_fieldsを取得します。コレクションアイテムのcollection_fieldごとにfield_valueがあります。
モデル
class Item < ActiveRecord::Base
belongs_to :collection
has_many :field_values, :dependent => :destroy
has_many :collection_fields, :through => :collection
accepts_nested_attributes_for :field_values, :allow_destroy => true
end
class Collection < ActiveRecord::Base
has_many :items, :dependent => :destroy
has_many :collection_fields, :dependent => :destroy
end
class CollectionField < ActiveRecord::Base
belongs_to :collection
belongs_to :field
has_many :items, :through => :collection
has_many :field_values, :dependent => :destroy
end
class Field < ActiveRecord::Base
has_many :collection_fields
end
class FieldValue < ActiveRecord::Base
belongs_to :item
belongs_to :collection_field
end
コントローラ
def new
@item = Item.new
@item.collection = Collection.find(params[:collection])
@item.collection.collection_fields.each do |cf|
@item.collection_fields << cf
end
def edit
@item = Item.find(params[:id])
見る
<%= form_for(@item, :html => { :multipart => true }) do |f| %>
<% @item.collection_fields.each do |cf| %>
<% f.label cf.field.name %>
<%= f.fields_for :field_values, cf.field_values.find_or_create_by_item_id(@item.id) do |fv| %>
<%= fv.text_field :valore %>
このコードはeditメソッドで正常に機能していますが、新しいアイテムを追加しようとすると、次のようになります。
ID=のアイテムのID=213のFieldValueが見つかりませんでした
これらのフォームフィールドを正しく実装するにはどうすればよいですか?