Ransack: How to persist ransack gem searching parameters in rails

Created on 1 Aug 2013  路  8Comments  路  Source: activerecord-hackery/ransack

I'm using ransack gem for searching users based on their company and active/inactive parameter. This works fantastic when used alone. but i want to make use of both simultaniously. for example if i select company first and then select active/inacitve user then company name should persist.

Also is there facility in ransack to keep both values persisted when i click back or agian on users.

Most helpful comment

I have made the gem for this:
https://github.com/richardrails/ransack_memory

All 8 comments

Please use the session functionality in Rails to persist your required search values across requests.

Thanks, Yes i have used it same way..
But i thaught there would be a way to do ransack way..

No, there is no magical Ransack way of storing session values. Please use the features Rails provides to you.

On Fri, Aug 2, 2013 at 4:26 PM, rakesh-ostwal [email protected]
wrote:

Thanks, Yes i have used it same way..

But i thaught there would be a way to do ransack way..

Reply to this email directly or view it on GitHub:
https://github.com/ernie/ransack/issues/265#issuecomment-21988664

If someone is interesetd, 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.

@waiting-for-dev thank you - would you also know how one can clear all search parameters at the click of a button?

@BKSpurgeon In the example passing clear=true as param will clean search parameters

I have made the gem for this:
https://github.com/richardrails/ransack_memory

@richardrails great effort! Feel free to do a PR on the Ransack README to point to your gem.

Was this page helpful?
0 / 5 - 0 ratings