1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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.
This commit is contained in:
Aaron Patterson 2012-05-16 17:32:00 -07:00
commit 08212956a7
2 changed files with 12 additions and 2 deletions

View file

@ -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)

View file

@ -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)