Skip to content

Commit 953543a

Browse files
committed
Merge pull request rails#37434 from giraffate/fix_eager_loading_with_limit_and_join_has_many
Fix eager load for no :has_many with limit and joins for :has_many
1 parent 7b6e25c commit 953543a

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

activerecord/lib/active_record/relation/finder_methods.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,8 @@ def apply_join_dependency(eager_loading: group_values.empty?)
376376
)
377377
relation = except(:includes, :eager_load, :preload).joins!(join_dependency)
378378

379-
if eager_loading && !using_limitable_reflections?(join_dependency.reflections)
379+
reflections = join_dependency.reflections + joins_values.map { |joins_value| reflect_on_association(joins_value) }.reject(&:blank?)
380+
if eager_loading && !using_limitable_reflections?(reflections)
380381
if has_limit_or_offset?
381382
limited_ids = limited_ids_for(relation)
382383
limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids)

activerecord/test/cases/finder_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1329,6 +1329,12 @@ def test_with_limiting_with_custom_select
13291329
assert_equal [0, 1, 1], posts.map(&:author_id).sort
13301330
end
13311331

1332+
def test_eager_load_for_no_has_many_with_limit_and_joins_for_has_many
1333+
relation = Post.eager_load(:author).joins(:comments)
1334+
assert_equal 5, relation.to_a.size
1335+
assert_equal relation.limit(5).to_a.size, relation.to_a.size
1336+
end
1337+
13321338
def test_find_one_message_on_primary_key
13331339
e = assert_raises(ActiveRecord::RecordNotFound) do
13341340
Car.find(0)

0 commit comments

Comments
 (0)