I have a Company model that has_many
Address(es) and many Phone(s).
Address(es) belong_to
Company as do Phone(s).
My problem is that I don't understand how to edit
a Company's particular Adress and Phone.
In my edit
action, I call up the specific record and assign it to an instance variable (i.e. @address = some scoped searched for the specific address I want), and then in my fields_for
I references this child's attributes, ex:
<%= f.fields_for :addresses, @address do |address| %>
A) I'm not sure if this is the way to do it. The documentation on how to access a parent's specific child for editing is sparse.
B) While this works fine if the update
succeeds, when it fails and I render :edit
the view presents additional fields with the parent's current child (the one I specified in my edit
action + another child -- seemingly the next record in line).
So basically, my form is extended with two children when the render :edit
is called. Weird.
What's the deal with this? How do nested attributes work? Is there a better way to manage forms with multiple associated models?
Thanks.
It sounds like you are using the fields_for helper outside of its purpose here. From what you've described, you want to edit an address outside of its parents relationship. If that's the case you'll edit that address in its own form (and likely its own controller) using the form_for helper.
The fields_for would be used if you wanted to do any CRUD operations in the same form as the parent thereby leveraging the accepts_nested_attributes_for functionality.