Skip to content

Commit

Permalink
Includes stale record in StaleObjectError
Browse files Browse the repository at this point in the history
  • Loading branch information
fabrik42 committed Oct 14, 2011
1 parent 401d00d commit 410fa4c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
9 changes: 9 additions & 0 deletions activerecord/lib/active_record/errors.rb
Expand Up @@ -99,6 +99,15 @@ class PreparedStatementInvalid < ActiveRecordError
#
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
class StaleObjectError < ActiveRecordError
attr_reader :record

def initialize(record)
@record = record
end

def message
"Attempted to update a stale object: #{record.class.name}"
end
end

# Raised when association is being configured improperly or
Expand Down
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/locking/optimistic.rb
Expand Up @@ -103,7 +103,7 @@ def update(attribute_names = @attributes.keys) #:nodoc:
affected_rows = connection.update stmt

unless affected_rows == 1
raise ActiveRecord::StaleObjectError, "Attempted to update a stale object: #{self.class.name}"
raise ActiveRecord::StaleObjectError, self
end

affected_rows
Expand All @@ -127,7 +127,7 @@ def destroy #:nodoc:
affected_rows = self.class.unscoped.where(predicate).delete_all

unless affected_rows == 1
raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object: #{self.class.name}"
raise ActiveRecord::StaleObjectError, self
end
end

Expand Down
19 changes: 18 additions & 1 deletion activerecord/test/cases/locking_test.rb
Expand Up @@ -125,6 +125,24 @@ def test_lock_new
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end

def test_lock_exception_record
p1 = Person.new(:first_name => 'mira')
assert_equal 0, p1.lock_version

p1.first_name = 'mira2'
p1.save!
p2 = Person.find(p1.id)
assert_equal 0, p1.lock_version
assert_equal 0, p2.lock_version

p1.first_name = 'mira3'
p1.save!

p2.first_name = 'sue'
error = assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
assert_equal(error.record.object_id, p2.object_id)
end

def test_lock_new_with_nil
p1 = Person.new(:first_name => 'anika')
p1.save!
Expand All @@ -141,7 +159,6 @@ def test_touch_existing_lock
assert_equal 1, p1.lock_version
end


def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
Expand Down

0 comments on commit 410fa4c

Please sign in to comment.