简体   繁体   English

Rails:如何过滤结果?

[英]Rails: How to filter results?

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 . 在我的Users控制器的索引操作中,我能够捕获与ActiveRecord :: Relation对象@userscurrent_user属于同一城市的所有用户。 In my view I am able to iterate through @users and display the results. 在我看来,我能够遍历@users并显示结果。 What I'd like to do is give the current_user further options to filter the results. 我想做的是给current_user更多选项来过滤结果。 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选择过滤器,例如:

  1. Minimum Age and Maximum Age (Drop Down) 最低年龄和最大年龄(下拉)
  2. Religion (Drop down of checkboxes) 宗教(下拉复选框)
  3. Diet (Drop down of checkboxes) 饮食(下拉复选框)
  4. And so on. 等等。

Once the current_user makes the selections and clicks on filter, the results will be filtered based on the criteria selected. 一旦current_user进行选择并点击过滤器,结果将根据所选标准进行过滤。 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

Which you could then call with 然后你可以打电话给

@users.filtered_by_age(min: 25, max: 52)

Best bet would either be Ranksack: https://github.com/ernie/ransack This provides search focused functionality. 最好的选择是Ranksack: https//github.com/ernie/ransack这提供了以搜索为中心的功能。

OR 要么

Squeel provides an easy to use interface for advanced querying for ActiveRecord: https://github.com/ernie/squeel Squeel为ActiveRecord提供了一个易于使用的高级查询界面: https//github.com/ernie/squeel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM