Every so often I need to make a simple dropdown menu of numbers in my app. And for some strange reason, I always seem to forget how to do this. So here are some examples for myself to use when I forget the next time.

  1. I need to let students pick the grade their in. In this example, we are only allowing students in grades 6-8. So I used this:
<%= f.select :grade, options_for_select([6,7,8]) %>

Looks like this:

  1. I need to find out how many parking vouchers someone will need. I want the 0 option to say, “No Parking Vouchers Needed”.
<%= f.select :parking, options_for_select(([["No Parking Vouchers Needed",0],[1,1],[2,2],[3,3]]), :selected => @attendee.parking ) %>

Looks like this:

  1. The only roles for users are either user or admin. In the model, I have this:
ROLES = %w[user admin]
def role_symbols
  [role.to_sym]
end

Then to make a dropdown menu of these choices, I use:

<%= f.collection_select :role, User::ROLES, :to_s, :humanize %>

Note that when using a form_tag, there is no corresponding collection_select_tag. Instead, you need to do this:

<%= select_tag :status, options_from_collection_for_select(Part::STATUS, :to_s, :titleize) %>

Looks like this:

  1. I have a table of workshops that people can attend. To make a dropdown list of the workshops in the table, I use:
<%= f.collection_select :workshop_id, Workshop.by_title, :id, :title, { :include_blank => true } %>

Looks like this: