Skip to content

Commit

Permalink
reloading an association will properly set attributes of instantiated…
Browse files Browse the repository at this point in the history
… objects. Thanks Brian Palmer [rails#5802 state:resolved]
  • Loading branch information
tenderlove committed Nov 16, 2010
1 parent 1395545 commit c801f23
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Expand Up @@ -379,7 +379,9 @@ def load_target
if i
@target.delete_at(i).tap do |t|
keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
t.attributes = f.attributes.except(*keys)
f.attributes.except(*keys).each do |k,v|
t.send("#{k}=", v)
end
end
else
f
Expand Down
21 changes: 21 additions & 0 deletions activerecord/test/cases/associations/has_many_associations_test.rb
Expand Up @@ -1282,4 +1282,25 @@ def test_include_method_in_has_many_association_should_return_true_for_instance_
comment = post.comments.build
assert post.comments.include?(comment)
end

def test_load_target_respects_protected_attributes
topic = Topic.create!
reply = topic.replies.create(:title => "reply 1")
reply.approved = false
reply.save!

# Save with a different object instance, so the instance that's still held
# in topic.relies doesn't know about the changed attribute.
reply2 = Reply.find(reply.id)
reply2.approved = true
reply2.save!

# Force loading the collection from the db. This will merge the existing
# object (reply) with what gets loaded from the db (which includes the
# changed approved attribute). approved is a protected attribute, so if mass
# assignment is used, it won't get updated and will still be false.
first = topic.replies.to_a.first
assert_equal reply.id, first.id
assert_equal true, first.approved?
end
end

0 comments on commit c801f23

Please sign in to comment.