diff options
author | Godfrey Chan <godfreykfc@gmail.com> | 2012-05-22 12:08:51 -0700 |
---|---|---|
committer | Godfrey Chan <godfreykfc@gmail.com> | 2012-05-22 12:08:51 -0700 |
commit | a5430024fd7e654d379b20373247033f68ec0a21 (patch) | |
tree | 8f9f727fc2ffd24c9cd46e858343f5bed6b9d16c | |
parent | 56b86a377a9fa7d63a6fce1e5801c4910dfc703e (diff) | |
download | rails-a5430024fd7e654d379b20373247033f68ec0a21.tar.gz rails-a5430024fd7e654d379b20373247033f68ec0a21.tar.bz2 rails-a5430024fd7e654d379b20373247033f68ec0a21.zip |
Restore the frozen state on rollback. Fixes #6417.
This is a 3-2-stable backport for #6420 which was merged into master.
Currently, when saving a frozen record, an exception would be thrown
which causes a rollback. However, there is a bug in active record that
"defrost" the record as a side effect:
>> t = Topic.new
=> #<Topic id: nil, ...>
>> t.freeze
=> #<Topic id: nil, ...>
>> t.save
RuntimeError: can't modify a frozen Hash
>> t.frozen?
=> false
>> t.save
=> true
This patch fixes the bug by explictly restoring the frozen state on the
attributes Hash after every rollback.
-rw-r--r-- | activerecord/lib/active_record/transactions.rb | 4 | ||||
-rw-r--r-- | activerecord/test/cases/transactions_test.rb | 10 |
2 files changed, 13 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 2c70d31b94..8c93f50926 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -327,7 +327,8 @@ module ActiveRecord @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 if @_start_transaction_state[:level] < 1 restore_state = remove_instance_variable(:@_start_transaction_state) - @attributes = @attributes.dup if @attributes.frozen? + was_frozen = @attributes.frozen? + @attributes = @attributes.dup if was_frozen @new_record = restore_state[:new_record] @destroyed = restore_state[:destroyed] if restore_state.has_key?(:id) @@ -336,6 +337,7 @@ module ActiveRecord @attributes.delete(self.class.primary_key) @attributes_cache.delete(self.class.primary_key) end + @attributes.freeze if was_frozen end end end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 203dd054f1..a9ccd00fac 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -362,6 +362,16 @@ class TransactionTest < ActiveRecord::TestCase end end + def test_rollback_when_saving_a_frozen_record + topic = Topic.new(:title => 'test') + topic.freeze + e = assert_raise(RuntimeError) { topic.save } + assert_equal "can't modify frozen Hash", e.message + assert !topic.persisted?, 'not persisted' + assert_nil topic.id + assert topic.frozen?, 'not frozen' + end + def test_restore_active_record_state_for_all_records_in_a_transaction topic_1 = Topic.new(:title => 'test_1') topic_2 = Topic.new(:title => 'test_2') |