Search code examples
ruby-on-railsransack

How to discard initial / default select option after first search with Ransack


If I specify a default :selected value for months/years below, then it always reverts to these after search. Is there a way to have the selects set to the selection for the search performed rather than the default after the page loads after the search?

I imagine this would require setting the default in the controller once and ignoring them if it is determined that the search is not the first or has other values selected.

<%= search_form_for @search, :html => {} do |f| %>
  <div class="control-group">
    <div class="controls form-inline">
      <%= f.select :rollout_month_eq, months, {:selected => months[Date.today.month - 1]} %>
      <%= f.select :rollout_year_eq, years, {:selected => years[1]} %>
      <%= f.submit "Apply" %>
    </div>
  </div>
<% end %>

Solution

  • It should be as simple as determining if the parameter is nil.

    <%= search_form_for @search, :html => {} do |f| %>
      <div class="control-group">
        <div class="controls form-inline">
          <%= f.select :rollout_month_eq, months, {:selected => params[:q].try(:[], :rollout_month_eq) || months[Date.today.month - 1]} %>
          <%= f.select :rollout_year_eq, years, {:selected => params[:q].try(:[], :rollout_year_eq) || years[1]} %>
          <%= f.submit "Apply" %>
        </div>
      </div>
    <% end %>
    

    Edited to reflect your parameter structure.