I\'m relatively new to rails and finally found the right way to use accepts_nested_attributes_for
.
However, there are some serious resources on the web who
So, the accepted answer just says why accepts_nested_attributes_for
is often a good solution, but never actually offers a solution on how to do it. And the example in the linked article will run into problems if you want to make your form accept a dynamic number of nested objects. This is the only solution I've found
https://coderwall.com/p/kvsbfa/nested-forms-with-activemodel-model-objects
For posterity this is the basics, but there's a bit more on the site:
class ContactListForm
include ActiveModel::Model
attr_accessor :contacts
def contacts_attributes=(attributes)
@contacts ||= []
attributes.each do |i, contact_params|
@contacts.push(Contact.new(contact_params))
end
end
end
class ContactsController < ApplicationController
def new
@contact_list = ContactListForm.new(contacts: [Contact.new])
end
end
and f.fields_for :contacts
should behave like an has_many
relationship, and easily handled by your form object.
If Contact
isn't an AR
model you'll need to spoof persisted?
as well.