collection_select default selected value

Hi,

I have some issues with setting the selected value. On my page, user selects a State from the drop down and other attributes and click on "Find". I want to set the default value of the drop down to the value selected prior to clicking "Find".

<%=collection_select(:state, :state_id, @states, :state_id, :state_name,           {:prompt => true, :selected => @selected_state},           {:style => 'width:200px;',                :onchange => remote_function(:url =>                  {:action => 'update_cities'},:with => "'state_id='+value")})%>

In my controller, if I have @selected_state = 1, the dropdown default value is shown in the UI. However, if I have @selected_state = state_id, the default value is not set.

Snippet of the code in my controller:

def find     state_id = params[:state][:state_id]

    @selected_state = state_id

    /* Some logic here */

    @states = State.find(:all)

   respond_to do |format|         format.html { render :action => "index" }    end end

Any pointers are appreciated. Thanks.

This is useful about collection_select :slight_smile:

http://shiningthrough.co.uk/blog/show/6

Thanks for the link Zt Di.

@selected_state = state_id.to_i works.

This is because state_id = params[:state][:state_id] returns a string.

Agree with you . Someone should merge the documentation there to the Rails API. The rails api's collection_select doc is somewhat incomplete or too brief. In short, it's not helpful.