views:

1144

answers:

3

How do I use Rails to create a drop-down selection box? Say if I have done the query:

@roles = Role.all

Then how do I display a box with all the @roles.name's ?

EDIT: After implementing the dropdown box. How do I make it respond to selections? Should I make a form?

A: 

This will create a drop down that displays the role name in the drop down, but uses the role_id as the value passed in the form.

select("person", "role_id", @roles.collect {|r| [ r.name, r.id ] }, { :include_blank => true })
erik
What I was about to post. Also you can find the API documentation for select at http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001592
Brandon Bodnár
+2  A: 

The form helper has a group of methods specifically written to create dropdown select boxes. Usually you'll use the *select_tag* method to create dropdown boxes, but in your case you can use collection_select, which takes an ActiveRecord model and automatically populates the form from that. In your view:

<%= collection_select @roles %>

Find out more about the Rails form helper here: http://guides.rubyonrails.org/form_helpers.html

Jamie Rumbelow
+3  A: 

use the collection_select helper http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001593

This will allow you to write something like:

collection_select(:user, :role_id, @roles, :id, :role_title, {:prompt => true})

And get

<select name="user[role_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>
David Burrows