Rails:如何过滤结果? [英] Rails: How to filter results?
问题描述
在我的用户控制器的索引操作中,我能够在 ActiveRecord::Relation 对象 @users
中捕获与 current_user
属于同一城市的所有用户.在我看来,我能够遍历 @users
并显示结果.我想做的是为 current_user
提供更多选项来过滤结果.我想在视图中添加一个表单和过滤器按钮,这将允许current_user 选择过滤器,例如:
In the index action of my Users controller, I am able to capture all users belonging to the same city as the current_user
in an ActiveRecord::Relation object @users
. In my view I am able to iterate through @users
and display the results. What I'd like to do is give the current_user
further options to filter the results. I want to add a form and filter button in the view, which will allow the current_user to select filters, such as:
- 最小年龄和最大年龄(下拉)
- 宗教(复选框下拉菜单)
- 饮食(复选框下拉)
- 等等.
一旦 current_user 做出选择并点击过滤器,结果将根据选择的条件进行过滤.我想知道如何构建查询来执行此操作?
Once the current_user makes the selections and clicks on filter, the results will be filtered based on the criteria selected. I want to know how to build a query to do this?
推荐答案
通过在用户模型中创建作用域方法,在没有库的情况下自己完成此操作也相对简单.例如:
It's also relatively simple to do this yourself without a library by creating scope methods in your user model. For example:
class User
def self.filtered_by_age(opts = {})
min = opts[:min]
max = opts[:max]
user = User.arel_table
if min && max
self.where(:age => min..max)
elsif min && !max
self.where(user[:age].gt(min))
elsif max && !min
self.where(user[:age].lt(max))
else
self.all
end
end
end
然后你可以打电话
@users.filtered_by_age(min: 25, max: 52)
这篇关于Rails:如何过滤结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!