Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

collapsing same table / column WHERE clauses to be OR [#4598 state:re…

…solved]
  • Loading branch information...
commit 00693209ecc222842949d7cab076f89890cbd507 1 parent 56c5820
@tenderlove tenderlove authored
Showing with 25 additions and 4 deletions.
  1. +25 −4 activerecord/lib/active_record/relation/query_methods.rb
View
29 activerecord/lib/active_record/relation/query_methods.rb
@@ -174,10 +174,7 @@ def build_arel
arel = build_joins(arel, @joins_values) unless @joins_values.empty?
- (@where_values - ['']).uniq.each do |where|
- where = Arel.sql(where) if String === where
- arel = arel.where(Arel::Nodes::Grouping.new(where))
- end
+ arel = collapse_wheres(arel, (@where_values - ['']).uniq)
arel = arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
@@ -198,6 +195,30 @@ def build_arel
private
+ def collapse_wheres(arel, wheres)
+ equalities = wheres.grep(Arel::Nodes::Equality)
+
+ groups = equalities.group_by do |equality|
+ left = equality.left
+ # table, column
+ [left.relation.name, left.name]
+ end
+
+ groups.each do |_, eqls|
+ head = eqls.first
+ test = eqls.inject(head) do |memo, expr|
+ expr == head ? expr : memo.or(expr)
+ end
+ arel = arel.where(test)
+ end
+
+ (wheres - equalities).each do |where|
+ where = Arel.sql(where) if String === where
+ arel = arel.where(Arel::Nodes::Grouping.new(where))
+ end
+ arel
+ end
+
def build_where(opts, other = [])
case opts
when String, Array
Please sign in to comment.
Something went wrong with that request. Please try again.