RoR select_tag default value & options

Solution 1:

If you are using select_tag without any other helper, then you can do it in html:

select_tag "whatever", "<option>VISA</option><option selected=\"selected\">MasterCard</option>"

Or with options_for_select:

select_tag "whatever", options_for_select([ "VISA", "MasterCard" ], "MasterCard")

Or with options_from_collection_for_select:

select_tag [SELECT_FIELD_NAME], options_from_collection_for_select([YOUR_COLLECTION], [NAME_OF_ATTRIBUTE_TO_SEND], [NAME_OF_ATTRIBUTE_SEEN_BY_USER], [DEFAULT_VALUE])

Example:

select_tag "people", options_from_collection_for_select(@people, 'id', 'name', '1')

Examples are from select_tag doc, options_for_select doc and from options_from_collection_for_select doc.

Solution 2:

Try this:

<%= select_tag(:option, options_for_select([["Option 1",1],["Option 2",2],["Option 3",3]], params[:option] ), class:"select") %>

works great in rails 5.

Solution 3:

For options_for_select

<%= select_tag("products_per_page", options_for_select([["20",20],["50",50],["100",100]],params[:per_page].to_i),{:name => "products_per_page"} ) %>

For options from collection for select

<%= select_tag "category","<option value=''>Category</option>" +  options_from_collection_for_select(@store_categories, "id", "name",params[:category].to_i)%>

Note that the selected value which you are specifying must be of type value. i.e. if value is in integer format then selected value parameter should also be integer.