From 19c80718afea8cf8f56ee68fcfbe325d54c02906 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sat, 21 Apr 2018 21:27:50 +0900 Subject: Ensure that `ids_reader` respects dirty target whether target is loaded or not Currently `ids_reader` doesn't respect dirty target when the target is not loaded yet unlike `collection.size`. I believe the inconsistency is a bug, fixes the `ids_reader` to behave consistently regardless of whether target is loaded or not. --- activerecord/lib/active_record/associations/collection_association.rb | 4 +++- activerecord/test/cases/associations/has_many_associations_test.rb | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index f233947fbd..d61d105544 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -45,6 +45,8 @@ module ActiveRecord def ids_reader if loaded? target.pluck(reflection.association_primary_key) + elsif !target.empty? + load_target.pluck(reflection.association_primary_key) else @association_ids ||= scope.pluck(reflection.association_primary_key) end @@ -212,7 +214,7 @@ module ActiveRecord def size if !find_target? || loaded? target.size - elsif @association_ids && target.empty? + elsif @association_ids @association_ids.size elsif !association_scope.group_values.empty? load_target.size diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index feb7390e2c..2e0a7ab1ab 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -989,7 +989,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 0, post.readers.size post.readers.reset post.readers.build - assert_equal [], post.reader_ids + assert_equal [nil], post.reader_ids assert_equal 1, post.readers.size end @@ -999,7 +999,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_empty post.readers post.readers.reset post.readers.build - assert_equal [], post.reader_ids + assert_equal [nil], post.reader_ids assert_not_empty post.readers end -- cgit v1.2.3