带有多个新子模型实例的 Rails 3 多模型表单 [英] Rails 3 Multi Model Form with Multiple new instances of submodel

查看:40
本文介绍了带有多个新子模型实例的 Rails 3 多模型表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以多模型形式展示了三个模型.

I have three models presented in a multi-model form.

class Parent < ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  has_many :other_children
  accepts_nested_attributes_for :other_children
end

class OtherChild < ActiveRecord::Base
  belongs_to :child
end

= form_for @parent do |f|
  # fields for parent
  = f.fields_for :children, @parent.children do |cf|
    = cf.fields_for :other_children, @parent.children do |ocf|
      # fields_for other child
    = cf.fields_for :other_children, @parent.children.new do |ocf|
      # fields_for other child

这有效,除非我通过 jquery 复制第二组子字段.更清楚地说,带有新 other_child 模型的 fields_for 有一个创建按钮,它会触发一些 jquery,例如 $(new_child_form).clone().insertBefore($(new_child_form)) 允许多个孩子模型要在同一个表单中添加提交.我知道我可以通过 ajax 单独提交每个子表单,但这不是我想要的.

This works except when I duplicate the second set of child fields via jquery. To be more clear, the fields_for with the new other_child model has a create button which trigger some jquery such as $(new_child_form).clone().insertBefore($(new_child_form)) allowing more than one child model to be added in the same form submit. I know I could submit each child form individually via ajax but this is not what I want.

Rails 获得了多个 parent[children_attributes][0][other_children_attributes][1] 并且似乎只使用了最后一个.有什么想法吗?

Rails is getting more than one parent[children_attributes][0][other_children_attributes][1] and only seems to use the last one. Any ideas?

推荐答案

您可以使用或不使用 jQuery 进行克隆.我通过让一个链接调用 Javascript 来解决这个问题,该 Javascript 插入元素但根据当前时间生成一个唯一 ID.如果您确实使用 jQuery 进行克隆,则必须确保更新克隆字段的 ID,以便 Rails 将它们视为新的子项.Ryan BatesRailscasts 196-197 并且他的解决方案继续适用于 Rails 3.

You can do this with or without using jQuery to clone. I solved this problem by having a link invoke Javascript that inserted elements but generated a unique ID based on the current time. If you do go with jQuery for cloning you have to be sure to update the IDs of the cloned fields so Rails treats them as new children. Ryan Bates illustrates how to do this in Railscasts 196-197 and his solution continues to work with Rails 3.

这篇关于带有多个新子模型实例的 Rails 3 多模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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