Edit Multiple Model Objects in Single Form

Hi Guys,

I'm having a little bit of trouble editing multiple model objects in a
single form. I've got a model Person with two attributes: name and
gender. For simplicity, gender can be a text input.

I'd like to be able to display all Person objects (name and gender) in
a form. So, each model object gets its own row.

In my controller, I fetch the objects with:

@people = Person.find(:all)

In my view, I loop through @people and render a form:

<% for person in @people %>
  <div>
    <span><%= person.name %>:</span>
    <span><%= text_field :person, :gender %></span>
  </div>
<% end %>

I've built plenty of forms that handle attributes from a single model
object. How would I edit multiple objects within a single form? In
specific, I'm not sure how to set the name attribute in the gender
field. And, i'm not sure how to deal with the params hash in my
controller to update the models.

Thanks in advance,
Raj

Yeah, that is not going to work. Have a look here:
http://railscasts.com/episodes/165-edit-multiple

Darian Shimy

If you are okay with mass assignment, do this instead:

    <% form_for(@people) do |person| %>
  <% fields_for(person) do |f| %>
      <!-- form fields go here -->
  <% end %>
    <% end %>

Of course, your create method will need to handle multiple records too,
rather than the defaults created by scaffolding.

Hi Todd,

Thanks for the help.

I'm getting the following message:

undefined method `person_person_person_path'

Hi Todd,

I was able to get the form to render properly. I'm still unclear
about how to set the values of the field_for fields and access them in
the controller code. When I use the following code, only one form
value is getting submitted.

<% form_tag do %>
<% @people.each do |person| %>
   <% fields_for(person) do |f| %>
     <div>
       <%= person.name %>:
       <%= f.text_field :age %>
     </div>
     <% end %>
   <% end %>
<%= submit_tag %>
<% end %>

Thanks,
Raj