Wed, 02 Aug 06

Helpful error messages when active record objects fail validation (in tests)

I posted a while back about displaying the reasons for an active record model failing validation.

I knew the code was hacky and nasty but didn’t realise quite how bad until I noticed how simply (1 line) the same thing was implemented in Rails 1.1 (and above).

Although it’s only useful for people still on Rails 1.0, I made a quick plugin that backports this change. I don’t really want to put it in my subversion repository, so have just pasted the necessary code below.

# File init.rb
require File.dirname(__FILE__) + '/lib/record_invalid'

# File record_invalid.rb
module ActiveRecord

  class RecordInvalid < ActiveRecordError
    def initialize(record)
      @record = record
      super("Validation failed: \#{@record.errors.full_messages.join(", ")}")


To create a plugin from this, create the following structure in your rails_app/vendor/plugins directory.

|--init.rb (copy contents of code above)
   |--record_invalid.rb (copy content of code above)