Skip to content

Commit

Permalink
Make HABTM#create behave the same as << with after_add callbacks. Closes
Browse files Browse the repository at this point in the history
 #11374 [freels]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9224 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
NZKoz committed Apr 4, 2008
1 parent 50538fb commit 36b8073
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,14 @@ def finding_with_ambiguous_select?(select_clause)
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
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/associations/callbacks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,21 @@ def test_has_and_belongs_to_many_add_callback
"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)
Expand Down

0 comments on commit 36b8073

Please sign in to comment.