class

ActiveRecord::RecordNotSaved

v7.2.3 - Show latest stable - Superclass: ActiveRecordError

Raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and {ActiveRecord::Base.update_attribute!}[rdoc-ref:Persistence#update_attribute!] methods when a record failed to validate or cannot be saved due to any of the before_* callbacks throwing :abort. See ActiveRecord::Callbacks for further details.

class Product < ActiveRecord::Base
  before_save do
    throw :abort if price < 0
  end
end

Product.create! # => raises an ActiveRecord::RecordNotSaved

Attributes

[R]record

Files

  • activerecord/lib/active_record/errors.rb

1Note

ActiveRecord::RecordNotSaved can be triggered by accidental false return values in callbacks

tadman ยท Jun 3, 20099 thanks

You may have this exception raised if any of the defined callbacks such as ActiveRecord::Base#before_save or ActiveRecord::Base#before_create return false.

This can happen accidentally. For example:

class MyModel < ActiveRecord::Base
before_save :assign_default_foo

protected
def assign_default_foo
  self.foo = false
end
end

Since assign_default_foo leaves a false value on the stack, the model will not be saved. A way around this is to simply leave nil or an empty return instead:

class MyModel < ActiveRecord::Base
before_save :assign_default_foo

protected
def assign_default_foo
  self.foo = false
  nil
end
end