AssociationCollection#include? working properly for objects added with build method [#3472 state:resolved]

This commit is contained in:
Marcelo Giorgi
2010-09-04 12:12:21 -03:00
committed by Aaron Patterson
parent 9b78af95be
commit 96c19ff7cc
4 changed files with 38 additions and 1 deletions

View File

@@ -332,6 +332,7 @@ module ActiveRecord
def include?(record)
return false unless record.is_a?(@reflection.klass)
return include_in_memory?(record) if record.new_record?
load_target if @reflection.options[:finder_sql] && !loaded?
return @target.include?(record) if loaded?
exists?(record)
@@ -503,6 +504,18 @@ module ActiveRecord
args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] ||
@target.any? { |record| record.new_record? } || args.first.kind_of?(Integer))
end
def include_in_memory?(record)
if @reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
@owner.send(proxy_reflection.through_reflection.name.to_sym).each do |source|
source_reflection_target = source.send(proxy_reflection.source_reflection.name)
return true if source_reflection_target.respond_to?(:include?) ? source_reflection_target.include?(record) : source_reflection_target == record
end
false
else
@target.include?(record)
end
end
end
end
end

View File

@@ -819,4 +819,9 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_queries(0) { david.projects.columns; david.projects.columns }
end
def test_include_method_in_has_and_belongs_to_many_association_should_return_true_for_instance_added_with_build
project = Project.new
developer = project.developers.build
assert project.developers.include?(developer)
end
end

View File

@@ -1221,5 +1221,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
EOF
end
end
def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
post = Post.new
comment = post.comments.build
assert post.comments.include?(comment)
end
end

View File

@@ -343,4 +343,18 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
lambda { authors(:david).very_special_comments.delete(authors(:david).very_special_comments.first) },
].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
def test_include_method_in_association_through_should_return_true_for_instance_added_with_build
person = Person.new
reference = person.references.build
job = reference.build_job
assert person.jobs.include?(job)
end
def test_include_method_in_association_through_should_return_true_for_instance_added_with_nested_builds
author = Author.new
post = author.posts.build
comment = post.comments.build
assert author.comments.include?(comment)
end
end