From b07b97057fba21cbccca9a81630173a88406175a Mon Sep 17 00:00:00 2001 From: Graham Turner Date: Tue, 17 Apr 2018 21:56:33 -0400 Subject: Loaded associations should not run a new query when size is called Already loaded associations were running an extra query when `size` was called on the association. This fix ensures that an extra query is no longer run. Update tests to use proper methods --- activerecord/lib/active_record/associations/collection_association.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/associations') diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 671c4c56df..f233947fbd 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -212,6 +212,8 @@ module ActiveRecord def size if !find_target? || loaded? target.size + elsif @association_ids && target.empty? + @association_ids.size elsif !association_scope.group_values.empty? load_target.size elsif !association_scope.distinct_value && !target.empty? @@ -231,7 +233,7 @@ module ActiveRecord # loaded and you are going to fetch the records anyway it is better to # check collection.length.zero?. def empty? - if loaded? + if loaded? || @association_ids size.zero? else target.empty? && !scope.exists? -- cgit v1.2.3