DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails Update Multiple Records With One Form Action

06.22.2009
| 14617 views |
  • submit to reddit
        // reports table has 3 columns: "name", "pub_date" and a boolean field "current"
//
// i want to display all records (or subset) in a form and modify the columns for each field at will...
//
// app/controllers/reports_controller.rb:

  def index
    @reports = Report.find_all_by_current(1)
  end

  def edit_reports
    @reports = Report.find(:all)
  end
  
  def update_reports
    Report.update(params[:report].keys, params[:report].values)
    flash[:notice] = 'Reports were successfully updated.'
    redirect_to :action => "index"
  end

// app/views/reports/index.html.erb:

<table>
  <tr>
    <th>Current</th>
    <th>Publication date</th>
    <th>Name</th>
  </tr>
  <% @reports.each do |report| %>
    <tr>
      <td><%=h report.current %></td>
      <td><%=h report.pub_date %></td>
      <td><%=h report.name %></td>
    </tr>
  <% end %>
</table>
<%= link_to 'edit', :action => "edit_reports" %>

// app/views/reports/edit_reports.html.erb:

<% form_for :report, :url => {:action => 'update_reports'} do -%>
  <table>
    <tr>
      <th>Current</th>
      <th>Publication date</th>
      <th>Name</th>
    </tr>
    <% @reports.each do |report| %>
      <% fields_for "report[]", report do |report_fields| %>
    <tr>
      <td><%= report_fields.check_box :current %></td>
      <td><%= report_fields.date_select :pub_date %></td>
      <td><%= report_fields.text_field :name %></td>
    </tr>
      <% end %>
    <% end %>
  </table>
 <%= submit_tag 'Update' %>
<% end %>