Skip to content

Instantly share code, notes, and snippets.

@rvanlieshout
Created February 21, 2012 10:10
Show Gist options
  • Save rvanlieshout/1875602 to your computer and use it in GitHub Desktop.
Save rvanlieshout/1875602 to your computer and use it in GitHub Desktop.
Filter scope
Save filter_scope.rb in your lib/ and make sure you lib/ is in your autoload path (I beleive that's default). Then add the following statement in your model:
include FilterScope
Now you're able to use .filter on your model:
Booking.filter(params[:search], [:name, :company, :site])
# Include this module in your ActiveRecord model to gain a filter scope
# Filter applies the supplied query to given attributes (or all attributes if none are given)
#
# example:
#
# User.filter('Bob', [:first_name, :last_name])
#
# returns all users with 'bob' in their first or last name
module FilterScope
def self.included(base)
base.class_eval do
scope :filter, lambda { |query, attributes|
return if query.blank?
collection = self
attributes = collection.new.attributes unless attributes
query.split(/\s/).each do |phrase|
conditions = [""]
attributes.each do |attribute|
conditions[0] += attribute.to_s + " LIKE ? OR "
conditions.push "%#{phrase}%"
end
conditions[0] = conditions[0].sub(/ OR $/,"")
collection = collection.where(conditions)
end
collection
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment