Rails: How to filter results?

2019-01-26 20:26发布

问题:

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