I can't seem to find the syntax to add a class to a select tag generated by Rails collection_select
. Some help?
-
1Can you give some example what you want to do? I don't understand your question. – klew Dec 22 '09 at 16:49
-
Sure... I'm using rails' <%= f.collection_select ... %> to generate: I just want it to be: – tybro0103 Dec 22 '09 at 16:54
3 Answers
Many Rails helpers take multiple hash arguments. The first is usually the options to control the helper itself, and the second is the html_options where you specifiy custom ids, classes etc.
The method definition looks like this:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
You'll notice the multiple '= {}' in the params list. To use this, the first set of options that you would specify must actually be enclosed in braces:
collection_select(:user, :title, UserTitle.all, :id, :name, {:prompt=>true}, {:class=>'my-custom-class'})
If you don't have any options to specify besides the html class, then just put an empty hash placeholder:
collection_select(:user, :title, UserTitle.all, :id, :name, {}, {:class=>'my-custom-class'})
Additional API documentation is available at: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

- 3,028
- 1
- 21
- 11
-
1Here's an extension of this answer showing how to modify .css style and use jQuery onchange events `<%= collection_select(:question , :text, Question.all , :id, :text, {:prompt => 'Select Question...'}, {:class=>'input', :name=>'normalSelect', :id=>'normalSelect', :style=>'width:50%', :onchange=>"$('#accordion').accordion('activate',2);$('#blind').show('blind', 500)"}) %>` – wantrapreneur Feb 09 '12 at 18:35
= f.collection_select :category_id, Category.order(:name), :id, :name, {}, {class: "store-select"}

- 7,479
- 5
- 46
- 47
Just in case, I was struggling with the same problem, I share my result, I was trying just putting {},{}
, so I had to be more explicit putting like this: options = {}, html_options = {}
, because it did not work for me.
<div class="field">
<%= form.label :country_id %>
<%= form.collection_select :country_id, @countries,:id, :name, options = {:prompt => 'Select a Country...'},
html_options = {class: "dropdown"}%>
</div>
Regards!

- 455
- 6
- 5