Ransack: Dropdown select menu reset to default option selection after form submit

Created on 24 Jun 2015  路  5Comments  路  Source: activerecord-hackery/ransack

I'm using Ransack to filter dates using a dropdown select menu like below:

<%= search_form_for @q do |f| %>
  <%= f.label :date_eq, "Date" %>
  <%= f.select :date_eq, options_for_select([
        ['Today', Time.zone.today],
        ['Tomorrow', Time.zone.tomorrow],
        [(Time.zone.today + 2).strftime("%d %b %A"), Time.zone.today + 2],
        [(Time.zone.today + 3).strftime("%d %b %A"), Time.zone.today + 3],
        [(Time.zone.today + 4).strftime("%d %b %A"), Time.zone.today + 4],
        [(Time.zone.today + 5).strftime("%d %b %A"), Time.zone.today + 5],
        [(Time.zone.today + 6).strftime("%d %b %A"), Time.zone.today + 6]
      ]) %>
  <%= f.submit "Filter" %>
<% end %>

When I click the submit button it does filter the selections according to the selected date but the dropdown option reset to the first option. This doesn't happen with collection_select however:

<%= f.label :city_id_eq, "City" %>
<%= f.collection_select :city_id_eq, @cities, :id, :name, include_blank: 'All' %>

Help?

Most helpful comment

@hisyam try this

<%= search_form_for @q do |f| %>
  <%= f.label :date_eq, "Date" %>
  <%= f.select :date_eq, options_for_select([
        ['Today', Time.zone.today],
        ['Tomorrow', Time.zone.tomorrow],
        [(Time.zone.today + 2).strftime("%d %b %A"), Time.zone.today + 2],
        [(Time.zone.today + 3).strftime("%d %b %A"), Time.zone.today + 3],
        [(Time.zone.today + 4).strftime("%d %b %A"), Time.zone.today + 4],
        [(Time.zone.today + 5).strftime("%d %b %A"), Time.zone.today + 5],
        [(Time.zone.today + 6).strftime("%d %b %A"), Time.zone.today + 6]
      ] , @q.date_eq)  %>
  <%= f.submit "Filter" %>
<% end %>

This should work

All 5 comments

@hisyam try this

<%= search_form_for @q do |f| %>
  <%= f.label :date_eq, "Date" %>
  <%= f.select :date_eq, options_for_select([
        ['Today', Time.zone.today],
        ['Tomorrow', Time.zone.tomorrow],
        [(Time.zone.today + 2).strftime("%d %b %A"), Time.zone.today + 2],
        [(Time.zone.today + 3).strftime("%d %b %A"), Time.zone.today + 3],
        [(Time.zone.today + 4).strftime("%d %b %A"), Time.zone.today + 4],
        [(Time.zone.today + 5).strftime("%d %b %A"), Time.zone.today + 5],
        [(Time.zone.today + 6).strftime("%d %b %A"), Time.zone.today + 6]
      ] , @q.date_eq)  %>
  <%= f.submit "Filter" %>
<% end %>

This should work

Thanks @harssh :+1:

Thanks @harssh I don't understand why but it does work.

@ghost Because the second paramater
options_for_select(container, selected = nil)

Thanks @harssh

Was this page helpful?
0 / 5 - 0 ratings