Neil
Neil

Reputation: 5178

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 = [email protected]

Ransack Documentation

Upvotes: 2

Views: 1474

Answers (1)

Prakash Laxkar
Prakash Laxkar

Reputation: 854

This will work for you.Thanks

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

Upvotes: 4

Related Questions