Last active
August 29, 2015 14:10
-
-
Save HotFusionMan/9c18e3089506baddef58 to your computer and use it in GitHub Desktop.
Add SQL "LIKE" clauses as ActiveRecord methods in a config/initializers/ file
This file contains hidden or 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
# 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