Reputation: 759
I can't seem to find any example of this so I wonder if I am doing it completely wrong or over-complicating it.
I have a Contacts model that belongs to an Installation. There are many different contact categories (auto, health, children..) So in the contacts/new form I want to have one form but multiple records can be added to the Contact model with this one form.
For example there is an Auto section with a contact fields, a Health section with a contact fields, ad one submit button. The only thing they have in common is what installation they belong to but I won't know that until they go to fill out the form.
Any help?
Upvotes: 0
Views: 150
Reputation: 50057
This is called a nested form
in rails, if you search you will find a lot of resources to help you further. For example, to get you started: check out this post on asciicasts (the readable version of railscasts.com).
Upvotes: 1
Reputation: 5714
You want to use the array syntax for form input, this will enable you to have an array of Contacts nested within your Installation form.
For instance, you might do:
<%= form_for @installation do |f| %>
<% for category in @categories do %>
# category is 'auto', 'health', 'children', etc.
<%= fields_for 'installation[#{category}][contacts][]' do |contact_f| %>
<%= contact_f.text_field :contact_data_field %>
# more fields here
<% end %>
<% end %>
<% end %>
Then in your installation controller you would need to deal with a params hash that looks something like:
{'installation' => { 'auto' => { 'contacts' => [ # an array of contact data hashes ] }}}
Check out understanding-parameter-naming-conventions in the rails guide on the form helpers.
ian.
Upvotes: 2