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?
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>
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 })
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With