alamodey
alamodey

Reputation: 14953

Drop down box in Rails

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?

Upvotes: 27

Views: 76937

Answers (4)

V-SHY
V-SHY

Reputation: 4125

Display role name as comboBox showing text (1st pluck argument) and it represents the role id

Controller

@roles = Role.pluck(:name, :id)

View

<%= select("role", "role_id", @roles) %>

params[:role][:role_id] passed to controller from view.

Upvotes: 1

David Burrows
David Burrows

Reputation: 5247

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>

Upvotes: 45

Jamie Rumbelow
Jamie Rumbelow

Reputation: 5095

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

Upvotes: 2

erik
erik

Reputation: 6436

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 })

Upvotes: 15

Related Questions