Skip to content

Instantly share code, notes, and snippets.

@clyfe
Created March 21, 2012 14:31
Show Gist options
  • Save clyfe/2147466 to your computer and use it in GitHub Desktop.
Save clyfe/2147466 to your computer and use it in GitHub Desktop.
Simple search with Squeel DSL
class Meal < ActiveRecord::Base
belongs_to :chef
has_many :meal_translations, inverse_of: :meal, dependent: :destroy
scope :simple_search, ->(terms) {
joins{meal_translations}.
joins{chef.locations.outer}.
where{
{ meal_translations => sift(:simple_search, terms) } |
{ chef.locations.zip_code.eq_any => terms }
}.uniq
}
end
class MealTranslation < ActiveRecord::Base
belongs_to :meal, inverse_of: :meal_translations
sifter :simple_search do |terms|
(title.like_any terms) | (body.like_any terms)
end
end
class Public::MealsController < PublicController
def index
@q = params[:q] || ''
terms = @q.split(/\W/).reject(&:blank?).uniq.map { |t| "%#{t}%" }
@meals = beginning_of_chain.includes(:meal_translations)
@meals = @meals.simple_search(terms) if terms.present?
@meals = @meals.page(params[:page])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment