Skip to content

Commit c801f23

Browse files
committed
reloading an association will properly set attributes of instantiated objects. Thanks Brian Palmer [rails#5802 state:resolved]
1 parent 1395545 commit c801f23

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

activerecord/lib/active_record/associations/association_collection.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,9 @@ def load_target
379379
if i
380380
@target.delete_at(i).tap do |t|
381381
keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
382-
t.attributes = f.attributes.except(*keys)
382+
f.attributes.except(*keys).each do |k,v|
383+
t.send("#{k}=", v)
384+
end
383385
end
384386
else
385387
f

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,4 +1282,25 @@ def test_include_method_in_has_many_association_should_return_true_for_instance_
12821282
comment = post.comments.build
12831283
assert post.comments.include?(comment)
12841284
end
1285+
1286+
def test_load_target_respects_protected_attributes
1287+
topic = Topic.create!
1288+
reply = topic.replies.create(:title => "reply 1")
1289+
reply.approved = false
1290+
reply.save!
1291+
1292+
# Save with a different object instance, so the instance that's still held
1293+
# in topic.relies doesn't know about the changed attribute.
1294+
reply2 = Reply.find(reply.id)
1295+
reply2.approved = true
1296+
reply2.save!
1297+
1298+
# Force loading the collection from the db. This will merge the existing
1299+
# object (reply) with what gets loaded from the db (which includes the
1300+
# changed approved attribute). approved is a protected attribute, so if mass
1301+
# assignment is used, it won't get updated and will still be false.
1302+
first = topic.replies.to_a.first
1303+
assert_equal reply.id, first.id
1304+
assert_equal true, first.approved?
1305+
end
12851306
end

0 commit comments

Comments
 (0)