rails select_tag selected value

Ruby on-Rails

Ruby on-Rails Problem Overview


For the code given below I wanted to keep the select box selected with the value that is passed.

But this doesn’t work:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,:selected=>2011) %>

Please advise me how to go about it.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Remove the :selected=> part.

Syntax:

options_for_select(@options, @selected_options)

Usage:

options_for_select(1..5, 3)  # creates a range 1..5 , with 3 as selected by default

Documentation

Solution 2 - Ruby on-Rails

<%= select_tag "page_type", options_for_select(@page_type.collect{ |u| [u.data_name, u.id]}, :selected=>@page.page_type), {:class =>"select_combobox",:onchange=>"reset_form(this.id,'page_type_msg');"} %>

this works for me :)

Solution 3 - Ruby on-Rails

Just to clarify @M Tariq Aziz answer:

Your code should look like this:

@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,2011) %>

The general format for select tag is:

<%= select_tag 'year', options_for_select(:collection, :selected) %>

Solution 4 - Ruby on-Rails

I was using a select box as part of a Search bar, so wanted to have the default first option selected on first presentation of the form, but then retain the chosen option thereafter. This works great:

<% styles = Styles.all.sort %>
<%= form_tag styles_path, :method => 'get' do %>
    <p>
		Search: style
		<%= select_tag :search_style, options_for_select(styles, selected: params[:search_style]) %>
		 with colour
		<%= text_field_tag :search_color, params[:search_color] %>
		<%= submit_tag "Search" %>
	</p>
<% end %>

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
QuestionlamrinView Question on Stackoverflow
Solution 1 - Ruby on-RailsM Tariq AzizView Answer on Stackoverflow
Solution 2 - Ruby on-Railsmanish nautiyalView Answer on Stackoverflow
Solution 3 - Ruby on-RailsharryaView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSnipsView Answer on Stackoverflow