@@ -1310,9 +1310,26 @@ def test_reorder_with_first_coerced
13101310 # We are not doing order duplicate removal anymore.
13111311 coerce_tests! :test_default_scope_order_with_scope_order
13121312
1313- # Leave it up to users to format selects/functions so HAVING works correctly .
1313+ # Order column must be in the GROUP clause .
13141314 coerce_tests! :test_multiple_where_and_having_clauses
1315+ def test_multiple_where_and_having_clauses_coerced
1316+ post = Post . first
1317+ having_then_where = Post . having ( id : post . id ) . where ( title : post . title )
1318+ . having ( id : post . id ) . where ( title : post . title ) . group ( :id ) . select ( :id )
1319+
1320+ assert_equal [ post ] , having_then_where
1321+ end
1322+
1323+ # Order column must be in the GROUP clause.
13151324 coerce_tests! :test_having_with_binds_for_both_where_and_having
1325+ def test_having_with_binds_for_both_where_and_having
1326+ post = Post . first
1327+ having_then_where = Post . having ( id : post . id ) . where ( title : post . title ) . group ( :id ) . select ( :id )
1328+ where_then_having = Post . where ( title : post . title ) . having ( id : post . id ) . group ( :id ) . select ( :id )
1329+
1330+ assert_equal [ post ] , having_then_where
1331+ assert_equal [ post ] , where_then_having
1332+ end
13161333
13171334 # Find any limit via our expression.
13181335 coerce_tests! %r{relations don't load all records in #inspect}
@@ -1322,10 +1339,18 @@ def test_relations_dont_load_all_records_in_inspect_coerced
13221339 end
13231340 end
13241341
1325- # I wanted to add `.order("author_id")` scope to avoid error: Column "posts.id" is invalid in the ORDER BY
1326- # However, this pull request on Rails core drops order on exists relation. https://github.com/rails/rails/pull/28699
1327- # so we are skipping all together.
1342+ # Order column must be in the GROUP clause.
13281343 coerce_tests! :test_empty_complex_chained_relations
1344+ def test_empty_complex_chained_relations_coerced
1345+ posts = Post . select ( "comments_count" ) . where ( "id is not null" ) . group ( "author_id" , "id" ) . where ( "legacy_comments_count > 0" )
1346+
1347+ assert_queries ( 1 ) { assert_equal false , posts . empty? }
1348+ assert_not_predicate posts , :loaded?
1349+
1350+ no_posts = posts . where ( title : "" )
1351+ assert_queries ( 1 ) { assert_equal true , no_posts . empty? }
1352+ assert_not_predicate no_posts , :loaded?
1353+ end
13291354
13301355 # Can't apply offset without ORDER
13311356 coerce_tests! %r{using a custom table affects the wheres}
0 commit comments