Updating Multiple Fields in Rails

Posted by Brian in Rails, snacks (April 23rd, 2007)

Just a quick one today…. I always have to look this one up.

Let’s say you have a guestbook and you want to approve multiple entries quickly. Rails has a built-in method for handling that, although it’s poorly documented.

Assuming your model “Entry” has an “approved” attribute that maps to a boolean field in the database, you might make a form like this:

<% form_tag :action=>"approve" do %>

<% @entries.each do |@entry| %>

Posted at<%=@entry.created_at %> by
<%=@entry.email %>

<%=h(@entry.body) %>

Approved? <%=check_box "@entry[]", "approved" %>

<% end %>

<%= submit_tag "Moderate Entries" %>
<% end %>

The key here is that you’re iterating over the items in the collection and using an instance variable to hold each one (@entry). Normally, a check_box helper looks like this:

<%=check_box "entry", "approved" %>

If you use the check_box helper with an array as the first parameter, you can create an array of entries that can all be sent to the back-end.

<%=check_box "entry[]", "approved" %>

Rails puts the primary key of the entry inside of the square-brackets, thus causing them to group nicely.

Your params hash will look like this:

"commit"=>"Moderate Selected Entries",

That’s the hard part. The action that receives the POST request looks like this

def moderate
Entry.update(params[:entry].keys, params[:entry].values)
flash[:notice] = "Successfully modified the approval flags for all records."
redirect_to :action=>"index"

Yeah, you read that right… no looping. The “update” class method on an ActiveRecord object can take either an ID or an array of IDs as the first parameter, and a hash of names and values or an array of hashes containing names and values for the second parameter. Since the form made the record ids as the keys in the hash, calling params[:entry].keys gives us the array of IDs we need for the first parameter. params[:entry].values gives us an array of the hashes we need for the second parameter.

Now, you can use this technique to do some simple mass-update pages if you needed to, but then it gets a little trickier.

I hope someone out there finds this useful.

2 Responses to ' Updating Multiple Fields in Rails '

Subscribe to comments with RSS or TrackBack to ' Updating Multiple Fields in Rails '.

  1. Darek said,
    on October 18th, 2007 at 11:34 am

    Yes, I found it really useful. Thanks!
    (Where did you found this informations?)

  2. on June 22nd, 2008 at 7:00 pm

    Helped a great deal, thanks!!


Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: