如何使用 Ransack 过滤结果 [英] How to filter results with Ransack

查看:35
本文介绍了如何使用 Ransack 过滤结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我网站上的搜索功能实施 Ransack.我尝试在 Ransack 上观看 Railscasts,并对如何实现它有了很好的了解.但是我遇到了一个我似乎无法弄清楚的问题.

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 是一个 ActiveRecord::Relation 对象.@users 本质上是捕获与 current_user 属于同一城市的所有用户.在我看来,我能够遍历 @users 并显示与 current_user 属于同一城市的所有用户.这一切都很好.现在我希望能够根据用户提供的年龄范围过滤这些结果.根据 Railcasts,我可以这样做:

@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

但后来我不再有相同的城市范围了.我想要的是默认显示与 current_user 属于同一城市的所有用户,然后按年龄过滤这些结果.

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.

推荐答案

Ransack 与 范围 配合使用,因此您可以轻松链接自己的范围.

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

假设 User.same_city_as 返回一个范围(一个 ActiveRecord::Relation 实例),你可以简单地这样做:

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

并且 @search.result 也返回一个范围,因此您可以对其进行进一步的修改,例如分页.

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

如果使用 Kaminari,这可能看起来像:

With Kaminari this could look like:

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

这篇关于如何使用 Ransack 过滤结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆