2014-11-03 46 views
0

我正在嘗試創建一個訂單表單,該表單也用作所有可用產品的列表。我有通過關聯has_many的模型,我設法創建collection_select字段來創建聯合模型上的記錄工作正常,但我無法弄清楚如何建立一個列表顯示每個產品並接受連接記錄的附加屬性。has_many通過窗體列出其他父項的每條記錄

我的模型(有些簡化,我也有圖片和這樣的):

class Supply < ActiveRecord::Base 
    attr_accessible :available, :name 

    has_many :order_lines 
    has_many :orders, through: :order_lines 

    accepts_nested_attributes_for :order_lines 

end 

class Order < ActiveRecord::Base 
    attr_accessible :month, :user_id, :order_lines_attributes 

    belongs_to :user 

    has_many :order_lines 
    has_many :supplies, through: :order_lines 

    accepts_nested_attributes_for :order_lines 

end 

class OrderLine < ActiveRecord::Base 
    attr_accessible :amount, :supply_id, :order_id 
    belongs_to :order 
    belongs_to :supply 

    validates_presence_of :amount 

end 

令控制器:

<%= f.fields_for :order_lines do |order_line| %> 
    <%= order_line.label :amount %> 
    <%= order_line.number_field :amount %> 
    <%= order_line.label :supply_id %> 
    <%= order_line.collection_select(:supply_id, @supplies, :id, :name) %> 
<% end %> 

到位:

def new 
    @order = Order.new 
    @supplies = Supply.available 
    @supplies.count.times { @order.order_lines.build } 

    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @supply_order } 
    end 
end 

ORDER_LINE從訂單表單字段這個我想要有一個order_line每個供應(具有名稱和其他屬性)的列表得到保存我如果有定義的金額。任何幫助感謝!

回答

0

只需爲每個供應添加一個order_item。取而代之的是:

@supplies.count.times { @order.order_lines.build } 

這樣做:

@supplies.each { |supply| @order.order_lines.build(supply: supply) } 

然後在您的訂單,你不需要爲supply_id的collection_select,只顯示名稱:

<%= order_line.object.supply.name %> 

確保您忽略空值的嵌套屬性:

accepts_nested_attributes_for :order_lines, reject_if: proc { |attr| attr.amount.nil? || attr.amount.to_i == 0 } 

您不需要Supply模型中的accep_nested_attributes_for。

+0

太好了,就是我在找的東西!我嘗試了類似的東西,但是我遺漏了「對象」部分,而Rails告訴我它沒有父類屬性的方法,所以我認爲關聯還沒有設置。 @ order.order_lines.build(supply:supply)雖然不能爲我工作(不能mass-assign protected attributes:supply),所以我不得不明確地使用@ order.order_lines.build(:supply_id => supply.id),並在視圖中爲其添加一個隱藏字段以使其保存。 謝謝! – user3069647 2014-11-04 09:28:25

+0

非常酷。只要記住你是如何做到這一點的,因爲你可能會再次遇到這種情況。 – 2014-11-04 13:19:56