diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb | 7 | ||||
-rw-r--r-- | activerecord/test/cases/associations/callbacks_test.rb | 15 |
2 files changed, 18 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index 923fbd8522..b06b618d5a 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -148,15 +148,14 @@ module ActiveRecord end private - def create_record(attributes) + def create_record(attributes, &block) # Can't use Base.create because the foreign key may be a protected attribute. ensure_owner_is_not_new if attributes.is_a?(Array) attributes.collect { |attr| create(attr) } else - record = build(attributes) - yield(record) - record + load_target + build_record(attributes, &block) end end end diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb index 17188e0b79..91b1af125e 100644 --- a/activerecord/test/cases/associations/callbacks_test.rb +++ b/activerecord/test/cases/associations/callbacks_test.rb @@ -94,6 +94,21 @@ class AssociationCallbacksTest < ActiveRecord::TestCase "after_adding#{david.id}"], ar.developers_log end + def test_has_and_belongs_to_many_after_add_called_after_save + ar = projects(:active_record) + assert ar.developers_log.empty? + alice = Developer.new(:name => 'alice') + ar.developers_with_callbacks << alice + assert_equal"after_adding#{alice.id}", ar.developers_log.last + + bob = ar.developers_with_callbacks.create(:name => 'bob') + assert_equal "after_adding#{bob.id}", ar.developers_log.last + + ar.developers_with_callbacks.build(:name => 'charlie') + assert_equal "after_adding<new>", ar.developers_log.last + end + + def test_has_and_belongs_to_many_remove_callback david = developers(:david) jamis = developers(:jamis) |