Created
November 13, 2014 00:50
-
-
Save hamajyotan/4e5d7c32595bbcbe10dc to your computer and use it in GitHub Desktop.
ActiveRecord::Relation reduce by 'OR'
This file contains 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
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