How to filter results with Ransack

2019-07-12 00:42发布

问题:

I am trying to implement Ransack for a search feature on my website. I tried watching the Railscasts on Ransack and got a pretty good idea of how to implement it. But I am running into an issue that I can't seem to figure out.

In the Index action of my Users controller, I have the following code:

def index
   @users = User.same_city_as(current_user)
end

@users is an ActiveRecord::Relation object. @users is essentially capturing all the users who belong to the same city as the current_user. In my view I am able to iterate through @users and display all users belonging to the same city as the current_user. This is all good. Now I want to be able to filter these results based on a range of age provided by the user. Per Railcasts, I could do this:

def index
  @search = User.search(params[:q])
  @Users = @search.result
end

But then I don't have the same city scope anymore. What I want is to display all users belonging to the same city as the current_user by default and then filter those results by age.

回答1:

Ransack works with scopes, so you can easily chain your own scopes.

Assuming User.same_city_as returns a scope (an ActiveRecord::Relation instance) you can simply do this:

@search = User.same_city_as(current_user).search(params[:q])
@users = @search.result

And @search.result returns a scope, too, so you can apply further modifications to it, like pagination for example.

With Kaminari this could look like:

@search = User.same_city_as(current_user).search(params[:q])
@users = @search.result.page(params[:page])