Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

update_attribute and updated_attributes! are now wrapped in a transac…

…tion

[#922 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
commit 99cdea7cbe69f7ea9ef82bdcf9502e47e9e4e07b 1 parent c2d13a9
@neerajdotname neerajdotname authored josevalim committed
View
8 activerecord/lib/active_record/base.rb
@@ -2664,12 +2664,20 @@ def update_attribute(name, value)
# Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will
# fail and false will be returned.
def update_attributes(attributes)
+ with_transaction_returning_status(:update_attributes_inside_transaction, attributes)
+ end
+
+ def update_attributes_inside_transaction(attributes) #:nodoc:
self.attributes = attributes
save
end
# Updates an object just like Base.update_attributes but calls save! instead of save so an exception is raised if the record is invalid.
def update_attributes!(attributes)
+ with_transaction_returning_status(:update_attributes_inside_transaction!, attributes)
+ end
+
+ def update_attributes_inside_transaction!(attributes) #:nodoc:
self.attributes = attributes
save!
end
View
23 activerecord/test/cases/transactions_test.rb
@@ -3,10 +3,12 @@
require 'models/reply'
require 'models/developer'
require 'models/book'
+require 'models/author'
+require 'models/post'
class TransactionTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
- fixtures :topics, :developers
+ fixtures :topics, :developers, :authors, :posts
def setup
@first, @second = Topic.find(1, 2).sort_by { |t| t.id }
@@ -34,6 +36,25 @@ def transaction_with_return
end
end
+ def test_update_attributes_should_rollback_on_failure
+ author = Author.find(1)
+ posts_count = author.posts.size
+ assert posts_count > 0
+ status = author.update_attributes(:name => nil, :post_ids => [])
+ assert !status
+ assert_equal posts_count, author.posts(true).size
+ end
+
+ def test_update_attributes_should_rollback_on_failure!
+ author = Author.find(1)
+ posts_count = author.posts.size
+ assert posts_count > 0
+ assert_raise(ActiveRecord::RecordInvalid) do
+ author.update_attributes!(:name => nil, :post_ids => [])
+ end
+ assert_equal posts_count, author.posts(true).size
+ end
+
def test_successful_with_return
class << Topic.connection
alias :real_commit_db_transaction :commit_db_transaction
View
2  activerecord/test/models/author.rb
@@ -106,6 +106,8 @@ def label
"#{id}-#{name}"
end
+ validates_presence_of :name
+
private
def log_before_adding(object)
@post_log << "before_adding#{object.id || '<new>'}"
Please sign in to comment.
Something went wrong with that request. Please try again.