1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

AR::RecordNotSaved & RecordNotDestroyed should include an error message

When `AR::Base.save!` or `AR::Base.destroy!` is called and an exception
is raised, the exception doesn't have any error message or has a weird
message like `#<FailedBulb:0x0000000907b4b8>`. Give a better message so
we can easily understand why it's failing to save/destroy.
This commit is contained in:
Yuki Nishijima 2015-01-06 04:31:08 -08:00
parent 2e7fd4a866
commit ad5824bde0
4 changed files with 8 additions and 5 deletions

View file

@ -71,9 +71,9 @@ module ActiveRecord
class RecordNotDestroyed < ActiveRecordError
attr_reader :record
def initialize(record)
def initialize(message, record = nil)
@record = record
super()
super(message)
end
end

View file

@ -148,7 +148,7 @@ module ActiveRecord
# Attributes marked as readonly are silently ignored if the record is
# being updated.
def save!(*args)
create_or_update(*args) || raise(RecordNotSaved.new(nil, self))
create_or_update(*args) || raise(RecordNotSaved.new("Failed to save the record", self))
end
# Deletes the record in the database and freezes this instance to
@ -193,7 +193,7 @@ module ActiveRecord
# and #destroy! raises ActiveRecord::RecordNotDestroyed.
# See ActiveRecord::Callbacks for further details.
def destroy!
destroy || raise(ActiveRecord::RecordNotDestroyed, self)
destroy || raise(RecordNotDestroyed.new("Failed to destroy the record", self))
end
# Returns an instance of the specified +klass+ with the attributes of the

View file

@ -2131,11 +2131,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
car = Car.create!
original_child = FailedBulb.create!(car: car)
assert_raise(ActiveRecord::RecordNotDestroyed) do
error = assert_raise(ActiveRecord::RecordNotDestroyed) do
car.failed_bulbs = [FailedBulb.create!]
end
assert_equal [original_child], car.reload.failed_bulbs
assert_equal "Failed to destroy the record", error.message
end
test 'updates counter cache when default scope is given' do

View file

@ -451,6 +451,7 @@ class CallbacksTest < ActiveRecord::TestCase
assert !david.save
exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! }
assert_equal exc.record, david
assert_equal "Failed to save the record", exc.message
end
david = ImmutableDeveloper.find(1)
@ -494,6 +495,7 @@ class CallbacksTest < ActiveRecord::TestCase
assert !david.destroy
exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
assert_equal exc.record, david
assert_equal "Failed to destroy the record", exc.message
end
assert_not_nil ImmutableDeveloper.find_by_id(1)