2

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.

pratski
  • 1,448
  • 2
  • 22
  • 37

1 Answers1

2

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])
Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
  • This works great. However, now I have another issue open. http://stackoverflow.com/questions/15849569/undefined-method-error-for-search-using-ransack-gem – pratski Apr 06 '13 at 10:12