Permalink
Browse files

Merge pull request #9115 from bensie/issue_5802

Don't call after_commit when creating through an association and save fails, fixes #5802
  • Loading branch information...
2 parents 5d58948 + caabed6 commit f36b80b3e8a1aae9e45af7c82be3917bc6277aa1 @steveklabnik steveklabnik committed Feb 13, 2013
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* Don't run after_commit callback when creating through an association
+ if saving the record fails.
+
+ *James Miller *
+
* Allow store accessors to be overrided like other attribute methods, e.g.:
class User < ActiveRecord::Base
@@ -286,8 +286,11 @@ def rollback_active_record_state!
end
# Call the after_commit callbacks
+ #
+ # Ensure that it is not called if the object was never persisted (failed create),
+ # but call it after the commit of a destroyed object
def committed! #:nodoc:
- run_callbacks :commit
+ run_callbacks :commit if destroyed? || persisted?
ensure
clear_transaction_record_state
end
@@ -5,9 +5,29 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :topics
+ class ReplyWithCallbacks < ActiveRecord::Base
+ self.table_name = :topics
+
+ belongs_to :topic, foreign_key: "parent_id"
+
+ validates_presence_of :content
+
+ after_commit :do_after_commit, on: :create
+
+ def history
+ @history ||= []
+ end
+
+ def do_after_commit
+ history << :commit_on_create
+ end
+ end
+
class TopicWithCallbacks < ActiveRecord::Base
self.table_name = :topics
+ has_many :replies, class_name: "ReplyWithCallbacks", foreign_key: "parent_id"
+
after_commit{|record| record.send(:do_after_commit, nil)}
after_commit(:on => :create){|record| record.send(:do_after_commit, :create)}
after_commit(:on => :update){|record| record.send(:do_after_commit, :update)}
@@ -93,6 +113,13 @@ def test_only_call_after_commit_on_create_after_transaction_commits_for_new_reco
assert_equal [:commit_on_create], @new_record.history
end
+ def test_only_call_after_commit_on_create_after_transaction_commits_for_new_record_if_create_succeeds_creating_through_association
+ topic = TopicWithCallbacks.create!(:title => "New topic", :written_on => Date.today)
+ reply = topic.replies.create
+
+ assert_equal [], reply.history
+ end
+
def test_call_after_rollback_after_transaction_rollsback
@first.after_commit_block{|r| r.history << :after_commit}
@first.after_rollback_block{|r| r.history << :after_rollback}

0 comments on commit f36b80b

Please sign in to comment.