Search code examples
ruby-on-railsselect

Ruby On Rails - Showing the default option with collection_select dependent on params


I'm using an outdated version of Rails (2.2).

I have a page that has a search filter. When I filter the options, I would like the Dropdown boxes to default to the filters I selected. The filters are stored as parameters in the URL. i.e.

filter[Issue+Header]=test&filter[in4User]=1&filter[Module]=3

What I search:

What I currently see when the page loads (as you can see, text boxes are re-populated, but dropdowns are not):

What I want to see when the page loads:

Example of a collection_select I am using:

<%= collection_select(:filter, "Client", Client.find(:all, :conditions => ['status = 0']), :ClientID, :Name, :include_blank => true) %>

Solution

  • What you need to do is pass in the :selected option into collection select, and pass the appropriate param as the value, so something like:

    <%= collection_select(:filter, "Client", Client.find(:all, :conditions => ['status = 0']), :ClientID, :Name, :include_blank => true, :selected => params[:filter]) %>
    

    That should select the client, assuming that the Client is in the collection.