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

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

This commit is contained in:
Marcelo Giorgi 2010-09-30 14:56:11 -03:00 committed by Aaron Patterson
parent 505b532605
commit ef6df93a8d
4 changed files with 39 additions and 0 deletions

View file

@ -363,6 +363,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)
@ -554,6 +555,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).map 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

@ -858,4 +858,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal new_developer.name, "Marcelo"
assert_equal new_developer.salary, 90_000
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

@ -1267,4 +1267,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal new_comment.type, "SpecialComment"
assert_equal new_comment.post_id, posts(:welcome).id
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

@ -435,4 +435,18 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert_equal new_subscriber.nick, "marklazz"
assert_equal new_subscriber.name, "Marcelo Giorgi"
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