module SearchableModels::Searchable::ClassMethods

Public Instance Methods

search_on(*args) click to toggle source

This method will setup a search query and add a ‘search` scope. When calling `search`, all the configured searches will be run. See the examples for different configurations of the search.

Example:

class Car < ActiveRecord::Base
  # simple search on one column (exact match)
  search_on :maker
  search_on :number_of_doors
end

Car.search(:maker => "Tesla")
Car.search(:maker => "VW", :number_of_doors => 2)

class Car < ActiveRecord::Base
  # fuzzy search (case insensitive)
  search_on :maker, :mode => :fuzzy
end

Car.search(:maker => "sla")

class Car < ActiveRecord::Base
  # Grouped searches
  search_on :maker, :mode => :fuzzy, :param => :query
  search_on :name, :mode => :fuzzy, :param => :query
end

Car.search(:query => "sla")

class Car < ActiveRecord::Base
  # search on association id
  belongs_to :fleet
  search_on :fleet_id
end

Car.search(:fleet_id => 33)

class Car < ActiveRecord::Base
  # search through on association
  belongs_to :fleet
  search_on :name, :through => :fleet
end

class Car < ActiveRecord::Base
  # using a scope (only one parameter scopes are valid)
  scope :imported_on, ->(date) { where(:import_date => date) }
  scope :import_date, :mode => :scope, :scope => :imported_on
end

Car.search(:import_date => "1975-12-12")

class Car < ActiveRecord::Base
  # acts-as-taggable-on support
  acts_as_taggable
  search_on :tags
end

Car.search(:tags => %w(small yellow))
Car.search(:tags => %w(yellow blue red), :tags_combination => :or)

Car.search(:import_date => "1975-12-12")
  # globalize support
  translates :name
  search_on :name, :mode => :fuzzy
end

Car.search(:name => "sla")
# File lib/searchable_models/searchable.rb, line 94
def search_on(*args)
  self._search_fields ||= {}
  self._search_fields.merge!(args.first => args.extract_options!)
end
search_ordered_by(field) click to toggle source

By the default, the order is based on column ‘id`. You can use this method to change the column.

Example

class Car < ActiveRecord::Base
  search_on(:name)
  search_ordered_by(:name)
end
# File lib/searchable_models/searchable.rb, line 108
def search_ordered_by(field)
  self._search_order = field
end

Private Instance Methods

_get_last_value(object) click to toggle source
# File lib/searchable_models/searchable.rb, line 194
def _get_last_value(object)
  return _get_last_value(object.first.last) if object.is_a?(Hash)
  object
end
_search_with_enum(results, field, value) click to toggle source
# File lib/searchable_models/searchable.rb, line 180
def _search_with_enum(results, field, value)
  results.where(field => send(field.to_s.pluralize).try(:[], value))
end
_search_with_scope(results, value, scope) click to toggle source
# File lib/searchable_models/searchable.rb, line 176
def _search_with_scope(results, value, scope)
  results.send(scope, value)
end