新手问题 [已解决] 求些 Rails 4 的嵌套表单的参考代码

chairy11 · September 25, 2014 · Last by chairy11 replied at September 30, 2014 · 2785 hits

问题:能否推荐些简单明了 Rails4 的嵌套表单的代码或是相关帖子可以学习一下的?

很常见的需求,一个 model(A),还有几个关联的 model(B、C、D),同时在一个表单里填写。 这时候,model A 是固定的一个,model B、C、D 则希望想加就加,想删就删,同时也可以更新。

看了几个 Railscast 视频

解决方案

好像没有什么解决方案,就是大概 《403 dynamic forms》中的思路。 我没有用 nested_formcocoon两个 gem。我用过程中,有些需要定制的地方,总感觉不太顺手。最后还是手写了。

自我反思

只是我之前各种自己把自己绕进去了,把简单的事情想复杂了。 之前有几个误区:

  1. 我一直用的是 field_for @parent.chidren.build, 虽然 name 能生成 parent[children][attr_name], 但我需要的 parent[children_attributes][xxx][attr_name], 后来发现只需要传入 field_for :children,把:children 作为一个属性来看,name 就能正确生成,param[parent] 就能正常获取,其它就会一切正常……
  2. 我学了很久,手上很多旧教材甚至还有 Rails 1, Rails 2 的。看过些例子,有模糊印象,却没有清晰的把握。有时大脑碎片很多,思路发散,反而把问题想了。比如看 《75 complex forms part-3》,因为里面有提到 new_task_attributes=(task_attributes),existing_task_attributes=(task_attributes) 两个方法,我就会想,那如果编辑过程中,有新提交的 children 和修改旧有的 children 情况存在,怎么区分? 后来发现,其实 rails 很聪明,旧有的,自动生成了一个隐藏的:id,带 id 的 children_attributes 会更新,不带 id 的 children_attributes 会新建。
  3. 另外,我之前一直没有 permit children_attributes[:id],这也是个问题。
  4. accepts_nested_attributes_for :children, allow_destroy: true, reject_if: :all_blank, 感觉 allow_destroy: true, reject_if: :all_blank 无法一起作用。

你需要的是 nested_form

https://github.com/nathanvda/cocoon

虽然搞复杂了,不过原理基本和 link_to_add_fields 一样。全部代码加起来才两百行,建议把每行代码都搞懂了。

#2 楼 @saiga 第一次学着去看一个 gem, 你说要看的代码,是在view_helperscocoon.js这两个里面的代码吗?

#1 楼 @messiahxu #2 楼 @saiga 谢谢你们,问题已经解决了:) 我没有用 gem,好像感觉一到要定制一点东西又要花很多力气,就还是手写了。

#2 楼 @saiga 额,有些地方还不那么懂,但我有尝试认真去理解,还抄了一些的……谢谢:)

You need to Sign in before reply, if you don't have an account, please Sign up first.