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
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 is getting more than one parent[children_attributes][0][other_children_attributes][1]
and only seems to use the last one. Any ideas?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With