Created
June 22, 2013 05:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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