Search code examples
ruby-on-railssessionruby-on-rails-4parametersransack

How do you auto-fill a Ransack search form with details from the previous search?


I have several filters that a user may apply to a search:

enter image description here

When the user checks a language and clicks filter, the a POST request is made to my search action:

def search
  index
  render :index
end

Which uses my index action:

def index
  @q = Listing.search(search_params)
  @listings = @q.result(distinct: true).page(params[:page])
end

@q is set by the Ransack Gem and is equal to the parameters submitted by the form:

q   {"languages_id_eq_any":["1"]} #this would be the param if 'French' was selected

To display matching objects (in my case, objects of the class Listing).

When the page is refreshed, the search results are appropriately filtered but my search form is all unchecked.

If the user filters by English, I would like the English language option to be checked after the search results are shown (so the user remembers which filter they used).

How would I do this?

I know I can "check" the checkbox by changing the form code from (see further below for full form code):

= check_box_tag('q[languages_id_eq_any][]', language.id ) 

to

= check_box_tag('q[languages_id_eq_any][]', language.id, checked: true )

But I'm not sure how to get the search parameter information available here - or if this is the most efficient direction to be going (manually setting each value throughout the form).


Here is the code for the form:

= simple_form_for @q, url: search_listings_path,
        html: { method: :post } do |f|
  - Language.all.each do |language|
    = check_box_tag('q[languages_id_eq_any][]', language.id )
    = language.name
  = f.button :submit, 'Filter'

Update after Toolz' answer below:

It's still not perfect (two helpers in one rather than one all-inclusive helper, but I extracted some of the long line into a helper:

def filtered_checkbox_value_by_index(name, index)
  symbol = "#{name}_id_eq_any".to_sym
  unless params[:q].nil? || params[:q][symbol].nil?
    params[:q][symbol].include?((index+1).to_s)
  end
end

So my checkbox code becomes:

- Language.all.each_with_index do |language, index|
  = check_box_tag('q[languages_id_eq_any][]', language.id, filtered_checkbox_value_by_index('languages', index))
  = language.name 
  = f.button :submit, 'Filter'

Solution

  • change

    - Language.all.each do |language|
      = check_box_tag('q[languages_id_eq_any][]', language.id )
    

    to

    - Language.all.each_with_index do |language, index|
      = check_box_tag('q[languages_id_eq_any][]', language.id, params[:q][:languages_id_eq_any].include?((index+1).to_s))