From 15d6e4dce7126fe24bce5cdb91d2ffee68648420 Mon Sep 17 00:00:00 2001 From: Ben Woosley Date: Mon, 28 May 2012 12:23:37 -0700 Subject: Fix that #exists? can produce invalid SQL: "SELECT DISTINCT DISTINCT" The combination of a :uniq => true association and the #distinct call in #construct_limited_ids_condition combine to create invalid SQL, because we're explicitly selecting DISTINCT, and also sending #distinct on to AREL, via the relation#distinct_value. Rather than build a select distinct clause in #construct_limited_ids_condition, I set #distinct! and pass just the columns into the select statement. This requires introducing a #columns_for_distinct method to return the select columns but not the statement itself. --- activerecord/lib/active_record/relation/finder_methods.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/lib/active_record/relation/finder_methods.rb') diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 72e9272cd7..ff825e52c1 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -245,9 +245,9 @@ module ActiveRecord def construct_limited_ids_condition(relation) orders = relation.order_values.map { |val| val.presence }.compact - values = @klass.connection.distinct("#{quoted_table_name}.#{primary_key}", orders) + values = @klass.connection.columns_for_distinct("#{quoted_table_name}.#{quoted_primary_key}", orders) - relation = relation.dup.select(values) + relation = relation.dup.select(values).distinct! id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values) ids_array = id_rows.map {|row| row[primary_key]} -- cgit v1.2.3