Rails: How to filter results?

人走茶凉 提交于 2019-12-18 06:59:54

问题


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:

  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. I want to know how to build a query to do this?


回答1:


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)



回答2:


Best bet would either be Ranksack: https://github.com/ernie/ransack This provides search focused functionality.

OR

Squeel provides an easy to use interface for advanced querying for ActiveRecord: https://github.com/ernie/squeel



来源:https://stackoverflow.com/questions/15474883/rails-how-to-filter-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!