开发者

fields_for with through relation

开发者 https://www.devze.com 2023-03-21 12:47 出处:网络
Item gets the collection_fields from his collections. For each collection_field of the collection item may have a field_value

Item gets the collection_fields from his collections. For each collection_field of the collection item may have a field_value

models

class Item < ActiveRecord::Base
    belongs_to :collection
    has_many :field_values, :dependent => :destroy
    has_many :collec开发者_JS百科tion_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

controller

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])

view

<%= 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 %>

This code is working fine with the edit method, but when I try to add a new item I get:

Couldn't find FieldValue with ID=213 for Item with ID=

How should I implement these form fields correctly?


I've finally worked out a solution. It's not so elegant, but it works

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号