Skip to content

Instantly share code, notes, and snippets.

@imme5150
Forked from oelmekki/any_of.rb
Last active January 3, 2016 00:19
Show Gist options
  • Save imme5150/8382276 to your computer and use it in GitHub Desktop.
Save imme5150/8382276 to your computer and use it in GitHub Desktop.
# Add this to an initializer file to extend ActiveRecord
# You can pass in an array of hashes. The key/values of your hashes will be joined w/ ANDs
# The hashes in the array will be joined w/ ORs
# You can also pass in an array of strings or arrays
class ActiveRecord::Base
def self.any_of( queries )
queries = queries.map do |query|
query = where( query ) if [ String, Hash ].any? { |type| query.kind_of? type }
query = where( *query ) if query.kind_of?( Array )
query.arel.constraints.reduce( :and )
end
where( queries.reduce( :or ) )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment