Rails: How to filter results? -
in index action of users controller, able capture users belonging same city current_user
in activerecord::relation object @users
. in view able iterate through @users
, display results. i'd give current_user
further options filter results. want add form , filter button in view, allow current_user select filters, such as:
- minimum age , maximum age (drop down)
- religion (drop down of checkboxes)
- diet (drop down of checkboxes)
- and on.
once current_user makes selections , clicks on filter, results filtered based on criteria selected. want know how build query this?
it's relatively simple without library creating scope methods in user model. 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 call with
@users.filtered_by_age(min: 25, max: 52)
Comments
Post a Comment