Skip to content

Instantly share code, notes, and snippets.

@joxxoxo
Last active December 14, 2015 08:19
Show Gist options
  • Save joxxoxo/5056888 to your computer and use it in GitHub Desktop.
Save joxxoxo/5056888 to your computer and use it in GitHub Desktop.
Add 'or' and 'and_not' methods to AR::Relation
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