Skip to content

Instantly share code, notes, and snippets.

@lleger
Created June 22, 2013 05:00
Show Gist options
  • Save lleger/5835934 to your computer and use it in GitHub Desktop.
Save lleger/5835934 to your computer and use it in GitHub Desktop.
**Simple Searchable Concern** To use, simply drop this in `app/models/concerns`, include it in the model you want to search (`include Searchable`) and declare which fields are searchable with `searchable_on`. The query currently performed is a simple conjoined `ilike`, but it could be easily extended to more robust queries.
module Searchable
extend ActiveSupport::Concern
included do
cattr_accessor :_searchable_fields
end
module ClassMethods
def searchable_on(*fields)
self._searchable_fields = fields
end
def search(term)
if term && _searchable_fields
query = _searchable_fields.collect { |field| "#{field} ilike :term" }.join(" or ")
where(query, term: "%#{term}%")
else
scoped
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment