ruby-on-rails-3 – Rails 3多模型表单,包含多个子模型的新实例
发布时间:2020-12-17 03:12:11 所属栏目:百科 来源:网络整理
导读:我有三个模型以多模型形式呈现. class Parent ActiveRecord::Base has_many :children accepts_nested_attributes_for :childrenendclass Child ActiveRecord::Base belongs_to :parent has_many :other_children accepts_nested_attributes_for :other_chil
我有三个模型以多模型形式呈现.
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单独提交每个子表单,但这不是我想要的. Rails获得多个父[children_attributes] [0] [other_children_attributes] [1]并且似乎只使用最后一个.有任何想法吗? 解决方法
您可以使用或不使用jQuery进行克隆.我通过链接调用插入元素的Javascript但基于当前时间生成唯一ID来解决此问题.如果您使用jQuery进行克隆,则必须确保更新克隆字段的ID,以便Rails将它们视为新子项.
Ryan Bates说明了如何在
Railscasts 196-
197中执行此操作,并且他的解决方案继续与Rails 3一起使用.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |