aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAaron Patterson <aaron.patterson@gmail.com>2012-05-16 17:32:00 -0700
committerAaron Patterson <aaron.patterson@gmail.com>2012-05-16 17:32:00 -0700
commit08212956a74de5e424077c4b5cf8ea5744fad46e (patch)
tree6eb2296e4825fc583cfc8592d888b88624ffc8eb
parentfc3b3b92a68c634a69ae4987a70f272c9f3f774e (diff)
parentf31670d0270342f37846082ac1a27fc6d3400a8a (diff)
downloadrails-08212956a74de5e424077c4b5cf8ea5744fad46e.tar.gz
rails-08212956a74de5e424077c4b5cf8ea5744fad46e.tar.bz2
rails-08212956a74de5e424077c4b5cf8ea5744fad46e.zip
Merge pull request #5453 from JonRowe/patch_uniq_has_and_belongs_to_many_when_already_loaded
When Active Record has already loaded a unique association `.size` returns the wrong number.
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb8
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb6
2 files changed, 12 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 56ec4c5c23..3af5ff3eab 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -242,8 +242,12 @@ module ActiveRecord
# This method is abstract in the sense that it relies on
# +count_records+, which is a method descendants have to provide.
def size
- if !find_target? || (loaded? && !options[:uniq])
- target.size
+ if !find_target? || loaded?
+ if options[:uniq]
+ target.uniq.size
+ else
+ target.size
+ end
elsif !loaded? && options[:group]
load_target.size
elsif !loaded? && !options[:uniq] && target.is_a?(Array)
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 470f0c3fd3..a6daf54c01 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -333,6 +333,12 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 3, project.developers.size
end
+ def test_uniq_when_association_already_loaded
+ project = projects(:active_record)
+ project.developers << [ developers(:jamis), developers(:david), developers(:jamis), developers(:david) ]
+ assert_equal 3, Project.includes(:developers).find(project.id).developers.size
+ end
+
def test_deleting
david = Developer.find(1)
active_record = Project.find(1)