Skip to content

Commit

Permalink
collapsing same table / column WHERE clauses to be OR [#4598 state:re…
Browse files Browse the repository at this point in the history
…solved]
  • Loading branch information
tenderlove committed Nov 18, 2010
1 parent 044e23d commit fdc5913
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,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?

Expand All @@ -200,6 +197,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
Expand Down

0 comments on commit fdc5913

Please sign in to comment.