Skip to content

Instantly share code, notes, and snippets.

@HotFusionMan
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HotFusionMan/9c18e3089506baddef58 to your computer and use it in GitHub Desktop.
Save HotFusionMan/9c18e3089506baddef58 to your computer and use it in GitHub Desktop.
Add SQL "LIKE" clauses as ActiveRecord methods in a config/initializers/ file
# Thanks to https://stackoverflow.com/questions/7051062/whats-the-best-way-to-include-a-like-clause-in-a-rails-query for the original code.
module ActiveRecord
module Querying
def match_scope_condition(column, query)
arel_table[column].matches("%#{query}%")
end
def matching(*args)
column_name, opts = args.shift, args.extract_options!
operator = opts[:operator] || :or
where(args.flatten.map { |query| match_scope_condition(column_name, query) }.inject(&operator))
end
end
end
# Example of defining a method specific to one particular column:
# class User
# scope :matching_email, ->(*query) { matching(:email, *query) }
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment