Search code examples
ruby-on-railsrubyactiverecordransack

How to chain scopes with ransack queries


A user submits a ransack query for finding employers. I want to first use a scope to filter down the records in the employers table, and then I want to run the ransack query on that activerecord::relation object returned from that scope.

Specifically in that order. It is important that the scope is run first because it returns only a select number of records which the ransack query can then further filter down. In my situation, running the ransack query first and then running the scope query on the return runs very slow because the ransack query may return many many records.

This sounds like the job of chaining queries together. I know how to chain regular scopes together:

# example
# `active`, `from_department_stores`, and `small_company` are all scopes
@employers = Employer.active.from_department_stores.small_company 

But I do not know how to chain ransack queries onto scopes, and do it in a manner where the scope is run first.

Code:

@q = Employer.ransack(params[:q])
# Pretty sure this will not work, but hopefully it provides a good idea
# of what I am trying to do
@employers = Employer.active.@q.result

Ransack Documentation


Solution

  • This will work for you.Thanks

    @employers = Employer.active.ransack(params[:q]).result