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

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

@ -148,7 +148,7 @@ def save(*args)
# 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 @@ def destroy
# 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

@ -2131,11 +2131,12 @@ def test_collection_association_with_private_kernel_method
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

@ -451,6 +451,7 @@ def test_deprecated_before_save_returning_false
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 @@ def test_deprecated_before_destroy_returning_false
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)