From 6a7fb9671303a267508d29fba39fb2b881bb5077 Mon Sep 17 00:00:00 2001 From: Carl Allen Date: Wed, 1 Dec 2010 19:01:24 -0800 Subject: [PATCH 2/2] reloading an association will properly set attributes of instantiated objects respecting overloading and composed_of --- .../associations/association_collection.rb | 2 +- .../associations/has_many_associations_test.rb | 13 ++++++++ activerecord/test/models/comment.rb | 31 ++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index abb17a1..57d7611 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -379,7 +379,7 @@ module ActiveRecord @target.delete_at(i).tap do |t| keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names) f.attributes.except(*keys).each do |k,v| - t.send("#{k}=", v) + t.send('write_attribute', k, v) end end else diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index fb772bb..d78c6dd 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1302,4 +1302,17 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal reply.id, first.id assert_equal true, first.approved? end + + def test_load_target_respects_overridden_assignment + post = Post.last + post.comments << AwesomeComment.new(:body => "Test Comment") + assert_equal post.comments[-1].body, Awesomeness.awesomeify("Test Comment") + end + + def test_load_target_respects_composed_of + post = Post.last + post.comments << SuperAwesomeComment.new(:body => Awesomeness.new("Test Comment")) + assert_equal post.comments[-1].body.to_s, Awesomeness.awesomeify("Test Comment") + end + end diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index 88061b2..f6d993a 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -23,6 +23,37 @@ class SpecialComment < Comment end end +class AwesomeComment < Comment + def body=(the_body) + self.send('write_attribute', 'body', Awesomeness.awesomeify(the_body)) + end + + def self.awesomeify(str) + "Awesome " + str + end +end + +class SuperAwesomeComment < Comment + composed_of :body, :class_name => 'Awesomeness', :mapping => [%w(body text)] +end + +class Awesomeness + def self.awesomeify(str) + "Awesome " + str + end + + attr_reader :text + + def initialize(awesome_text) + @text = awesome_text + end + + def to_s + self.class.awesomeify text + end +end + + class SubSpecialComment < SpecialComment end -- 1.7.3.2