diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 7f4be54dbb..a8bed82e19 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -14,7 +14,8 @@ *Pavel Evstigneev* -* Avoid `unscope(:order)` when `limit_value` is presented for `count`. +* Avoid `unscope(:order)` when `limit_value` is presented for `count` + and `exists?`. If `limit_value` is presented, records fetching order is very important for performance. We should not unscope the order in the case. diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 97a819c5af..55ded4c6d0 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -321,7 +321,7 @@ module ActiveRecord relation = apply_join_dependency(self, construct_join_dependency(eager_loading: false)) return false if ActiveRecord::NullRelation === relation - relation = relation.except(:select, :order).select(ONE_AS_ONE).limit(1) + relation = relation.except(:select, :distinct).select(ONE_AS_ONE).limit(1) case conditions when Array, Hash