Patrick
Patrick

Reputation: 3684

Ruby on Rails form_for select field with class

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.

Upvotes: 233

Views: 152632

Answers (4)

ThienSuBS
ThienSuBS

Reputation: 1622

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}

Upvotes: 7

Alex Onozor
Alex Onozor

Reputation: 7081

This work for me

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

Upvotes: 14

Paing Soe Thaw
Paing Soe Thaw

Reputation: 463

You can also add prompt option like this.

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

Upvotes: 32

MBO
MBO

Reputation: 30985

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

Upvotes: 513

Related Questions