Skip to content
This repository
Browse code

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.
  • Loading branch information...
commit a5430024fd7e654d379b20373247033f68ec0a21 1 parent 56b86a3
Godfrey Chan authored May 22, 2012
4  activerecord/lib/active_record/transactions.rb
@@ -327,7 +327,8 @@ def restore_transaction_record_state(force = false) #:nodoc:
327 327
         @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
328 328
         if @_start_transaction_state[:level] < 1
329 329
           restore_state = remove_instance_variable(:@_start_transaction_state)
330  
-          @attributes = @attributes.dup if @attributes.frozen?
  330
+          was_frozen = @attributes.frozen?
  331
+          @attributes = @attributes.dup if was_frozen
331 332
           @new_record = restore_state[:new_record]
332 333
           @destroyed  = restore_state[:destroyed]
333 334
           if restore_state.has_key?(:id)
@@ -336,6 +337,7 @@ def restore_transaction_record_state(force = false) #:nodoc:
336 337
             @attributes.delete(self.class.primary_key)
337 338
             @attributes_cache.delete(self.class.primary_key)
338 339
           end
  340
+          @attributes.freeze if was_frozen
339 341
         end
340 342
       end
341 343
     end
10  activerecord/test/cases/transactions_test.rb
@@ -362,6 +362,16 @@ def test_rollback_when_commit_raises
362 362
     end
363 363
   end
364 364
 
  365
+  def test_rollback_when_saving_a_frozen_record
  366
+    topic = Topic.new(:title => 'test')
  367
+    topic.freeze
  368
+    e = assert_raise(RuntimeError) { topic.save }
  369
+    assert_equal "can't modify frozen Hash", e.message
  370
+    assert !topic.persisted?, 'not persisted'
  371
+    assert_nil topic.id
  372
+    assert topic.frozen?, 'not frozen'
  373
+  end
  374
+
365 375
   def test_restore_active_record_state_for_all_records_in_a_transaction
366 376
     topic_1 = Topic.new(:title => 'test_1')
367 377
     topic_2 = Topic.new(:title => 'test_2')

0 notes on commit a543002

Please sign in to comment.
Something went wrong with that request. Please try again.