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:
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
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.
OR
Squeel provides an easy to use interface for advanced querying for ActiveRecord: https://github.com/ernie/squeel
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.