首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >accepts_nested_attributes_for和nested_form插件

accepts_nested_attributes_for和nested_form插件
EN

Stack Overflow用户
提问于 2010-02-05 04:20:44
回答 3查看 3.2K关注 0票数 3

我在_form.html.haml部分代码中有以下代码,它用于新建和编辑操作。(仅供参考,我使用Ryan Bates的插件nested_form)

代码语言:javascript
复制
.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

在新动作中工作正常...对于编辑操作,正如文档中所解释的,我必须添加已经存在的关联的:id,因此,我必须添加如下内容

代码语言:javascript
复制
= 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)

代码语言:javascript
复制
# 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 }
# ])

谢谢你的帮助。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-02-07 10:45:04

我发现了我的错误,以下是我学到的仅供参考:

当您使用具有多对多关联的accepts_nested_attributes_for时,请保留关联表的:id主键。

干杯

票数 1
EN

Stack Overflow用户

发布于 2010-05-07 08:41:13

当使用":_delete“而不是":_destroy”时,我的方法有效。我使用的是rails 2.3.4。Ruby 1.8.7

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

票数 1
EN

Stack Overflow用户

发布于 2010-02-05 09:08:20

Rails正式支持嵌套表单。您正在做的事情(特别是使用fields_for方法)可能与RAils内置的呈现fields_for的方式冲突。

下面是Rails方法的文档,用来做field_ for……非常详细:

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

我强烈建议你尝试内置的方式,而不是插件,因为它将继续得到几乎无限期的支持。

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2202882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档