fields_for with through relation



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])
<<p> 视图/strong>
<%= 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=213的字段值

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

我终于想出了一个解决办法。它不是那么优雅,但它可以工作

- @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

相关内容

  • 没有找到相关文章

最新更新