Last active
December 14, 2015 08:19
-
-
Save joxxoxo/5056888 to your computer and use it in GitHub Desktop.
Add 'or' and 'and_not' methods to AR::Relation
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
module ScopeOperators | |
def or(other). | |
left = arel.constraints.reduce(:and) | |
right = other.arel.constraints.reduce(:and) | |
scope = merge(other) | |
left ||= Arel::Nodes::Grouping.new(0) # take none if no conditions | |
right ||= Arel::Nodes::Grouping.new(0) # take none if no conditions | |
scope.where_values = [ Arel::Nodes::Grouping.new(left).or(Arel::Nodes::Grouping.new(right)) ] | |
scope | |
end | |
alias_method :|, :or | |
def and_not(other) | |
left = arel.constraints.reduce(:and) | |
right = other.arel.constraints.reduce(:and) | |
scope = merge(other) | |
right ||= Arel::Nodes::Grouping.new('1=1') # take all if no conditions | |
scope.where_values = [left, right.not].compact # to reject nil -> when there were no values | |
scope | |
end | |
end | |
ActiveSupport.on_load :active_record do | |
ActiveRecord::Relation.send(:include, ScopeOperators) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment