diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 311bf4dc0f92e764f387b4bff2636d3defc45420..e58c726e09620e4c52505c09462c98f8be49f75e 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -249,7 +249,7 @@ def apply_join_dependency(relation, join_dependency) end def construct_limited_ids_condition(relation) - orders = relation.order_values.map { |val| val.presence }.compact + orders = (relation.reorder_value || relation.order_values).map { |val| val.presence }.compact values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders) relation = relation.dup diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 88d7d47aea2c41db67f9c0a40eaf6c43a1b0f0e1..f1a341437f2a36b669a5adc2b328baf96ff28474 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -57,6 +57,16 @@ def test_should_count_distinct_results end end +class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase + fixtures :authors, :posts, :comments + + def test_should_generate_valid_sql + author = authors(:david) + # this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression + # if the reorder clauses are not correctly handled + assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.taggings_count DESC').last + end +end class HasManyAssociationsTest < ActiveRecord::TestCase