Skip to content

Commit 79a5338

Browse files
committed
Fix include? on strict-loaded HABTM association
Previously, trying to check whether a `new_record?` (`Post.new`) is `include?`d in a strict-loaded HABTM association would raise a `StrictLoadingViolationError` even when the HABTM association is already loaded. This commit fixes the issue by always using the `target` if the association is `loaded?` instead of querying the Through association (which is only needed when the association is dirty/has newly built records).
1 parent 5a7a59a commit 79a5338

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -259,10 +259,10 @@ def include?(record)
259259
klass = reflection.klass
260260
return false unless record.is_a?(klass)
261261

262-
if record.new_record?
263-
include_in_memory?(record)
264-
elsif loaded?
262+
if loaded?
265263
target.include?(record)
264+
elsif record.new_record?
265+
include_in_memory?(record)
266266
else
267267
record_id = klass.composite_primary_key? ? klass.primary_key.zip(record.id).to_h : record.id
268268
scope.exists?(record_id)

activerecord/test/cases/strict_loading_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,14 @@ def test_does_not_raise_on_eager_loading_a_habtm_relation_if_strict_loading_by_d
636636
end
637637
end
638638

639+
def test_does_not_raise_when_checking_if_new_record_included_in_eager_loaded_habtm_relation
640+
Developer.first.projects << Project.first
641+
642+
developer = Developer.includes(:projects).strict_loading.first
643+
644+
assert_nothing_raised { developer.projects.include?(Project.new) }
645+
end
646+
639647
def test_strict_loading_violation_raises_by_default
640648
assert_equal :raise, ActiveRecord.action_on_strict_loading_violation
641649

0 commit comments

Comments
 (0)