accepts_nested_attributes_for和nested_form插件 [英] accepts_nested_attributes_for and nested_form plugin

查看:249
本文介绍了accepts_nested_attributes_for和nested_form插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code在_form.html.haml部分,它使用新的和编辑的操作。 (仅供参考我用Ryan Ba​​tes的插件 nested_form

I've the following code in a _form.html.haml partial, it's used for new and edit actions. (fyi I use the Ryan Bates' plugin 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已经存在的关联,所以,我得添加类似

works fine for the new action... for the edit action, as explain in the doc, I've to add the :id of already existing associations, so, I've to add something like

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

我怎样才能获得价值?

How can I get the value?

下面是accepts_nested_attributes_for的文档,以供参考(来源:<一href="http://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L332" rel="nofollow">http://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L332)

Here is the doc of accepts_nested_attributes_for for reference (source: 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 }
# ])

感谢您的帮助。

Thanks for your help.

推荐答案

我发现我的错误,在这里我学到了什么供参考:

I found my error, here is what i learned fyi:

当你使用accepts_nested_attributes_for与多对多关联,保持:ID主键关联表

When you use accepts_nested_attributes_for with many to many associations, keep the :id primary key for the association table.

干杯

这篇关于accepts_nested_attributes_for和nested_form插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆