Home > Ruby on Rails > Rails Tip: Using select_tag with a collection

Rails Tip: Using select_tag with a collection

July 9th, 2007

In Agile Web Development with Rails, they have the following code snippet for working with a selection list and a collection.

<%=
  @users = User.find(:all, :o rder => "name").map {
    |u| [u.name, u.id]
  }
  form.select(:name, @users)
%>

This may work when using form_for, but I could not get a similar variant to work with form_tag. Instead, I had to do the following:

<%=
  @users = User.find(:all)
  select_tag(:id,
    options_from_collection_for_select(@users, :id, :name))
%>

If you don’t include the options_from_collection_for_select method, you get some very odd HTML output.

<select id="id" name="id">
  John Smith1John Doe2Jane Doe3Jane Smith4
</select>

There may be a simpler way of doing this, but after several hours of searching, this is what I found worked for me.

Categories: Ruby on Rails Tags:
  1. Thomas K
    December 13th, 2008 at 08:10 | #1

    Good example! Thanks

  2. December 22nd, 2008 at 16:48 | #2

    really thanks~

Comments are closed.