fields_for与通过关系

时间:2011-07-20 15:07:59

标签: ruby-on-rails ruby-on-rails-3 fields-for

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

我应该如何正确实现这些表单字段?

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案。它不是那么优雅,但它可以工作

- @collection.collection_fields.each do |cf|
    = f.label cf.field.name
    - if @item.new_record?
        = f.fields_for :field_values,  @item.field_values.build() do |field_value|
            = field_value.text_field :valore
            = field_value.hidden_field :collection_field_id, :value => cf.id
    - else
        = f.fields_for :field_values, @item.field_values.find_or_create_by_collection_field_id(cf.id) do |field_value|
            %td= field_value.text_field :valore