From 60b23ea1da1c119eaab6d07e5a03cf3b5d5577d4 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 14 May 2011 19:40:24 +0100 Subject: CollectionAssociation#merge_target_lists should write to the underlying attributes when copying, rather than using the assignment method --- .../lib/active_record/associations/collection_association.rb | 7 ++----- .../test/cases/associations/has_many_associations_test.rb | 10 ++++++++++ activerecord/test/models/bulb.rb | 4 ++++ activerecord/test/schema/schema.rb | 1 + 4 files changed, 17 insertions(+), 5 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index d551cb01f0..50825a50f0 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -405,17 +405,14 @@ module ActiveRecord mem_record = memory.delete(record) if mem_record - # FIXME: this call to record.attributes causes many NoMethodErrors - attributes = record.attributes - # Only try to assign attributes which exist on mem_record - shared = mem_record.attribute_names & attributes.keys + shared = mem_record.attribute_names & record.attribute_names # Don't try to assign the primary key, or attributes which have changed on mem_record excluded = ["id"] + mem_record.changes.keys (shared - excluded).each do |key| - mem_record.send("#{key}=", attributes[key]) + mem_record[key] = record[key] end mem_record diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index b149f5912f..0e33fa9c8e 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1445,4 +1445,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_not_equal target.object_id, ary.object_id end + + def test_merging_with_custom_attribute_writer + bulb = Bulb.new(:color => "red") + assert_equal "RED!", bulb.color + + car = Car.create! + car.bulbs << bulb + + assert_equal "RED!", car.bulbs.to_a.first.color + end end diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb index 643dcefed3..7d90963720 100644 --- a/activerecord/test/models/bulb.rb +++ b/activerecord/test/models/bulb.rb @@ -11,4 +11,8 @@ class Bulb < ActiveRecord::Base @scope_after_initialize = self.class.scoped end + def color=(color) + self[:color] = color.upcase + "!" + end + end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index c8a98f121d..d56cdd57b2 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -90,6 +90,7 @@ ActiveRecord::Schema.define do t.integer :car_id t.string :name t.boolean :frickinawesome + t.string :color end create_table "CamelCase", :force => true do |t| -- cgit v1.2.3