Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
alamodey Avatar asked Jun 15 '09 12:06

alamodey


4 Answers

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>
like image 51
David Burrows Avatar answered Nov 14 '22 07:11

David Burrows


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 })
like image 34
erik Avatar answered Nov 14 '22 06:11

erik


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

like image 3
Jamie Rumbelow Avatar answered Nov 14 '22 07:11

Jamie Rumbelow


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.

like image 1
V-SHY Avatar answered Nov 14 '22 07:11

V-SHY