Ruby on Rails form_for select field with class

Ruby on-Rails

Ruby on-Rails Problem Overview


I am beating my head against the wall on this one. I want to make a simple select tag using the f.select tag but nothing I do works. I put an example below:

<%= f.select(:object_field, ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 4'], :class => 'my_style_class')%>

Ok, so basically it is a simple list that once the form is submitted it places the value into the object_field. That all works, but viewing the page source the class tag is not included. It doesn't throw an error, it just skips it all together.

If anyone has any suggestions I would greatly appreciate it.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

Solution 2 - Ruby on-Rails

You can also add prompt option like this.

<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>

Solution 3 - Ruby on-Rails

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

Solution 4 - Ruby on-Rails

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickView Question on Stackoverflow
Solution 1 - Ruby on-RailsMBOView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPaing Soe ThawView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAlex OnozorView Answer on Stackoverflow
Solution 4 - Ruby on-RailsThienSuBSView Answer on Stackoverflow