2014-02-07 57 views
0

我有兩個型號,保留和表格,用的has_many通過與他們之間的關係的has_many連接表和模型的集合,即有一個叫做單獨的屬性:units_sold嵌套形式,通過協會

我的預訂模式:

class Reservation < ActiveRecord::Base 

    has_many :tables, through: :collections 
    has_many :collections 
end 

我的表模型:

class Table < ActiveRecord::Base 

    has_many :reservations, through: :collections 
    has_many :collections 
end 

終於收集模式:

class Collection < ActiveRecord::Base 

    belongs_to :table 
    belongs_to :reservation 
end 

例如:

9人在我的名字的保留(:units_sold)具有各2代表具有6:1容量,我想4人在一個表和5上的第二個表

reservation_params

def reservation_params 
    params.require(:reservation).permit(:name, :total_units, table_ids: [], 
           collection_attributes: [ :units_sold], 
           table_attributes: [:capacity, :title]) 
end 

和我的表單進行預約:我有目前這是

<%= form_for [current_user, @account, @reservation] do |f| %> 

<header> 
    <h1>Make your reservation</h1> 
</header> 

    <%= f.text_field :name,   placeholder: "Name" %> 
    <%= f.number_field :total_units,  placeholder: "How many people..." %> 
    <%= f.fields_for :collections do |c|%> 
     <% @tables.each do |p| %> 

      <label for="<%= p.title %>"><%= p.title %></label> 
      <%= c.number_field :units_sold,  placeholder: "People per table..." %> 
      <%= check_box_tag "reservation[table_ids][]", p.id %> 
     <% end %> 
    <% end %> 
    <%= f.submit "Save" %>  

<% end %> 

我該如何做預訂控制器中的reservation_params?和嵌套形式接受:units_sold爲每個表/預約協會

回答

0

首先,你應該這樣定義的關聯:

的has_many:收藏

的has_many:預訂,通過:收藏

如在,首先定義集合,然後通過集合進行保留。同樣,更新表模型中的關聯。

然後在確定的關聯後的預約模式,添加以下行:

accepts_nested_attributes_for:收藏

在reservation_params,關鍵的 「collection_attributes」 和 「table_attributes」 應爲 「collections_attributes」 和「tables_attributes 「 分別。

+0

我這樣做了,但是,當我放入預留模型時,它將使下列表單字段在f.number_field下消失:total_units – tvieira

+0

更新行<%= f.fields_for:collections do | c |%>到: <%= f.fields_for:collections,f.object.collections || f.object.collections.build do | c |%> 這將返回現有集合進行預留,如果沒有任何集合,它將初始化集合對象 – RB17

+0

我收到一個錯誤:units_sold方法undefined – tvieira