Skip to content

Instantly share code, notes, and snippets.

@hamajyotan
Created November 13, 2014 00:50
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 hamajyotan/4e5d7c32595bbcbe10dc to your computer and use it in GitHub Desktop.
Save hamajyotan/4e5d7c32595bbcbe10dc to your computer and use it in GitHub Desktop.
ActiveRecord::Relation reduce by 'OR'
require 'active_record/relation'
# Usage
#
# class User
# scope :foo, -> { where(name: 'foo') }
# scope :bar, -> { where(name: 'foo') }
# end
#
# > User.foo.or User.bar
# User Load (0.6ms) SELECT `users`.* FROM `users` WHERE ((`users`.`name` = 'foo' OR `users`.`name` = 'bar'))
#
module ReduceByOr
def or other
w1 = self.where_values.reduce(:and)
b1 = self.bind_values
w2 = other.where_values.reduce(:and)
b2 = other.bind_values
self.klass.where(w1.or w2).bind(b1 + b2)
end
end
ActiveRecord::Relation.include ReduceByOr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment