Skip to content

Instantly share code, notes, and snippets.

@jperrine
Created February 17, 2012 23:32
Show Gist options
  • Save jperrine/1856192 to your computer and use it in GitHub Desktop.
Save jperrine/1856192 to your computer and use it in GitHub Desktop.
scope :terms, lambda { |terms|
return if terms.blank?
composed_scope = joins(:user)
terms.split.each do |term|
term = '%' << term << '%' # Wrap the search term in % to achieve 'fuzzy' searching
composed_scope = composed_scope.where 'messages.body ILIKE :term', term: term
composed_scope = composed_scope.where 'users.first_name ILIKE :term or users.last_name ILIKE :term', term: term
end
composed_scope
}
Message.terms('test').to_sql
=> "SELECT \"messages\".* FROM \"messages\" INNER JOIN \"users\" ON \"users\".\"id\" = \"messages\".\"user_id\" WHERE (messages.body ILIKE '%test%') AND (users.first_name ILIKE '%test%' or users.last_name ILIKE '%test%') ORDER BY messages.id DESC"
Message.terms('test this shit').to_sql
=> "SELECT \"messages\".* FROM \"messages\" INNER JOIN \"users\" ON \"users\".\"id\" = \"messages\".\"user_id\" WHERE (messages.body ILIKE '%test%') AND (users.first_name ILIKE '%test%' or users.last_name ILIKE '%test%') AND (messages.body ILIKE '%this%') AND (users.first_name ILIKE '%this%' or users.last_name ILIKE '%this%') AND (messages.body ILIKE '%shit%') AND (users.first_name ILIKE '%shit%' or users.last_name ILIKE '%shit%') ORDER BY messages.id DESC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment