Item 从他的收藏中获取 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 %>
此代码在编辑方法中运行良好,但是当我尝试添加新项目时,我得到:
对于 ID= 的项目,找不到 ID=213 的 FieldValue
我应该如何正确实现这些表单域?