Skip to content

Commit

Permalink
Restore the frozen state on rollback. Fixes rails#6417.
Browse files Browse the repository at this point in the history
This is a 3-2-stable backport for rails#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
chancancode committed May 22, 2012
1 parent 56b86a3 commit a543002
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
4 changes: 3 additions & 1 deletion activerecord/lib/active_record/transactions.rb
Expand Up @@ -327,7 +327,8 @@ def restore_transaction_record_state(force = false) #:nodoc:
@_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)
Expand All @@ -336,6 +337,7 @@ def restore_transaction_record_state(force = false) #:nodoc:
@attributes.delete(self.class.primary_key)
@attributes_cache.delete(self.class.primary_key)
end
@attributes.freeze if was_frozen
end
end
end
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/transactions_test.rb
Expand Up @@ -362,6 +362,16 @@ def test_rollback_when_commit_raises
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')
Expand Down

0 comments on commit a543002

Please sign in to comment.