#10 new
kwatch

[PATCH] Enhanced to support :index_by option for form_for(), fields_for(), and fieldset_for().

Reported by kwatch | November 19th, 2008 @ 04:27 AM

A patch to enhance form_for(), fields_for(), and fieldset_for() to take :index_by option which helps you to generate same controls for several model objects.

For example:


<% @students.each do |student| %>
<%   id = student.id %>
<p>
  <%= text_field :name => "student[#{id}][name]", :value => student.name, :label => 'Name' %>
  <%= text_field :mail => "student[#{id}][mail]", :value => student.mail, :label => 'Mail' %>
</p>
<% end %>

...will be:


<% @students.each do |student| %>
<%=  fields_for student, :index_by => :id do %>
<p>
  <%= text_field :name, :label => 'Name' %>
  <%= text_field :mail, :label => 'Mail' %>
</p>
<%   end =%>
<% end %>

...if you apply the patch. The latter is more compact and readable than the former.

Both generate the same HTML such as:


<p>
  <label for="student_name_101">Name</label>
  <input type="text" name="student[101][name]" id="student_name_101" value="Foo" />
  <label for="student_mail_101">Mail</label>
  <input type="text" name="student[101][mail]" id="student_mail_101" value="foo@mail.com" />
</p>
<p>
  <label for="student_name_102">Name</label>
  <input type="text" name="student[102][name]" id="student_name_102" value="Bar" />
  <label for="student_mail_102">Mail</label>
  <input type="text" name="student[102][mail]" id="student_mail_102" value="bar@mail.com" />
</p>

This way makes for controller action to handle several model objects very easy.


  def update
    params[:student].each do |id, values|
      student = Student.get(id) or NotFound
      student.update_attributes(values)
      ...
    end
  end

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Shared Ticket Bins

People watching this ticket

Attachments

Pages