2010-02-04 86 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

相关问题