2010-02-04 33 views
3

我在_form.html.haml部分中有以下代碼,它用於新建和編輯操作。 (FYI我使用Ryan Bates的插件nested_formaccept_nested_attributes_for和nested_form插件

.fields 
    - f.fields_for :transportations do |builder| 
     = builder.collection_select :person_id, @people, :id, :name, {:multiple => true} 
     = builder.link_to_remove 'effacer' 
    = f.link_to_add "ajouter", :transportations 

正常工作新動作...... 的編輯操作,如DOC解釋,我已經添加的:已經ID現有的協會,所以,我必須添加像

= builder.hidden_field :id, ?the value? if ?.new_record? 

我怎樣才能得到的價值?

這裏是accepts_nested_attributes_for作參考文檔(來源:http://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L332

# Assigns the given attributes to the collection association. 
# 
# Hashes with an <tt>:id</tt> value matching an existing associated record 
# will update that record. Hashes without an <tt>:id</tt> value will build 
# a new record for the association. Hashes with a matching <tt>:id</tt> 
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the 
# matched record for destruction. 
# 
# For example: 
# 
# assign_nested_attributes_for_collection_association(:people, { 
# '1' => { :id => '1', :name => 'Peter' }, 
# '2' => { :name => 'John' }, 
# '3' => { :id => '2', :_destroy => true } 
# }) 
# 
# Will update the name of the Person with ID 1, build a new associated 
# person with the name `John', and mark the associatied Person with ID 2 
# for destruction. 
# 
# Also accepts an Array of attribute hashes: 
# 
# assign_nested_attributes_for_collection_association(:people, [ 
# { :id => '1', :name => 'Peter' }, 
# { :name => 'John' }, 
# { :id => '2', :_destroy => true } 
# ]) 

感謝您的幫助。

回答

1

,我發現我的錯誤,這裏是我FYI瞭解到:

當你accepts_nested_attributes_for使用具有多對多關聯,保持:對於關聯表ID主鍵。

乾杯

+0

你說什麼「保留:關聯表的主鍵」是什麼意思?由於rails文檔只提到1對n和1對1關聯http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for,我不知道如何用n對n來實現這一點。 – v4r 2012-06-27 18:17:54

0

Rails正式支持嵌套表單。你正在做什麼(特別是與fields_for方法)可能與RAils內置的渲染fields_for方法相沖突。

這裏的方式做fields_for的文檔Rails的...這是非常透徹:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M001605

我強烈建議你嘗試內置的方式,而不是插件,因爲這將繼續幾乎無限期地得到支持。

希望這會有所幫助!

+0

感謝您的回答。我通過使用accept_nested_attributes_for來使用內置的方式。使用插件爲我提供了刪除和添加鏈接的功能。我的問題與使用內置方式完全相關。正如accept_nested_attributes_for doc中所解釋的,我必須提供一個匹配現有關聯記錄的id值,這樣內置的功能將自動更新該記錄。乾杯 – denisjacquemin 2010-02-05 11:37:34

相關問題