Question

I'm using ransack for searching users based on their company and active/inactive parameter. This works well when used individually, but I want to make use of both simultaneously. For example, if I select company first and then select active/inactive user, then the company name should persist.

Second, is there a facility in ransack to keep both values persisted when I click back or again on users?

UPDATE :

This is my view:

= search_form_for @search, url: search_users_path, method: :post, html: { class: 'sort' } do |f|
  = f.label 'company:'
  = f.select :company_id_eq,
  Company.where('is_inactive = false').collect {|c| [ c.name, c.id ] },
  {:include_blank => 'All company users'}, :'data-remote' => true, class: 'searchSelect searchUserSelect'

  %div.sort_users
    = f.label 'sort Users:'
    = f.select :deleted_eq,
    [raw("<option value= 0 selected=#{session[:deleted]}>Active Users</option><option value= 1>Inactive Users</option>")],
    {}, :'data-remote' => true, class: 'searchSelect searchUserSelect', style: "width: 205px;"

This is my code in controller

@search = User.search(params[:q])
@users = @search.result.includes(:company).order("companies.name, last_name").page(params[:page]).per(20)
Was it helpful?

Solution

About filters persistence, I'm using the following before_action in ApplicationController:

def get_query(cookie_key)
  cookies.delete(cookie_key) if params[:clear]
  cookies[cookie_key] = params[:q].to_json if params[:q]
  @query = params[:q].presence || JSON.load(cookies[cookie_key])
end

Then, say for an Intervention model, I have the following:

class InterventionsController < ApplicationController
  before_action only: [:index] do
    get_query('query_interventions')
  end

  def index
    @q = Intervention.search(@query)
    @interventions = @q.result
  end
end

That way, if interventions_path is called without the q param, cookies['query_interventions'] is checked to access last persisted query. But when interventions_path is called with the q param, this new query is used and persisted for later use.

Also, if interventions_path is called with the clear param, the cookie is deleted.

Note this would raise a CookieOverflow exception if more than 4k are stored, but this is between 1024 and 4096 UTF-8 characters and it is usually ok. If not, you should use other kind of session storage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top