class

ActiveRecord::RecordInvalid

v2.0.3 - Show latest stable - Superclass: ActiveRecordError

Raised by save! and create! when the record is invalid. Use the record method to retrieve the record which did not validate.

  begin
    complex_operation_that_calls_save!_internally
  rescue ActiveRecord::RecordInvalid => invalid
    puts invalid.record.errors
  end

Attributes

[R]record

Files

  • activerecord/lib/active_record/validations.rb

3Notes

Clear and simple rescue

jqr · Feb 14, 20091 thank

noxyu3m, your code is rescuing all exceptions, not just ActiveRecord::RecordInvalid.

I think this syntax is a bit more clear than using the global variable.

def create
@model = Model.new(params[:model)
@model.save!
rescue => err                          # rescues all exceptions
logger.error(err.to_s)
end

Simple rescue

noxyu3m · Feb 14, 2009

Take it easy:

def create
@model = Model.new(params[:model)
@model.save!
rescue
logger.error(!$.to_s)
end

Global variable !$ refers to the Exception object.

Using global $! to address exception

schmidt · Apr 15, 2009

@noxyu3m: Your code is actually syntactically wrong. The global is called $!

Your code should have been:

def create
@model = Model.new(params[:model)
@model.save!
rescue
logger.error($!.to_s)
end

Although I would prefer

def create
@model = Model.new(params[:model)
@model.save!
rescue ActiveRecord::RecordInvalid
logger.error($!.to_s)
end

to only catch expected exceptions, just like the documentation proposed.