Fix relation.exists? with giving distinct, offset and order for joined table

The error happens in PostgreSQL when using `relation.exists?` with
`distinct`, `offset` and `order` for joined table.
However, the error does not happen if either `distinct` or `offset` is
removed. This behavior is confusing.

Fixes #36632
This commit is contained in:
Takayuki Nakata 2019-07-10 22:53:52 +09:00
parent 6e40b131d2
commit d9587feb5f
2 changed files with 6 additions and 1 deletions

@ -354,7 +354,7 @@ def construct_relation_for_exists(conditions)
conditions = sanitize_forbidden_attributes(conditions)
if distinct_value && offset_value
relation = limit(1)
relation = except(:order).limit(1)
else
relation = except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
end

@ -283,6 +283,11 @@ def test_exists_with_distinct_and_offset_and_select
assert_not Post.select(:body).distinct.offset(4).exists?
end
def test_exists_with_distinct_and_offset_and_eagerload_and_order
assert Post.eager_load(:comments).distinct.offset(10).merge(Comment.order(post_id: :asc)).exists?
assert_not Post.eager_load(:comments).distinct.offset(11).merge(Comment.order(post_id: :asc)).exists?
end
# Ensure +exists?+ runs without an error by excluding distinct value.
# See https://github.com/rails/rails/pull/26981.
def test_exists_with_order_and_distinct