5

One of the things that is driving me crazy with Rails is that I'll see a ROLLBACK message in the console with no reason attached to the rollback. This often leads me into hunting for some validation error, but it would nice to have a more detailed message.

Is there anyway to enabled more detailed logging for db rollbacks?

James McMahon
  • 48,506
  • 64
  • 207
  • 283

1 Answers1

5

You could use a after_rollback callback.

Create a module called RollbackLogger and place it inside your app/concerns directory

module RollbackLogger
  extend ActiveSupport::Concern

  included do
    after_rollback :log_status, on: [:create, :update]
  end

  def log_status
    Rails.logger.info "Rollback caused by: #{self.errors.full_messages}"
  end
end

then include this module in every ActiveRecord model:

class Foo < ActiveRecord::Base
  include RollbackLogger
end

Edit:

As Mr. Damien Roche suggests, you can create a new file inside the config/initializers directory and add the following line:

ActiveRecord::Base.send(:include, RollbackLogger)

All models will include the RollbackLogger module automatically.

Community
  • 1
  • 1
Chris Ledet
  • 11,458
  • 7
  • 39
  • 47
  • I'm pretty new to Rails, how would I do this across all models in a non-intrusive way? – James McMahon Oct 25 '13 at 20:37
  • 2
    @ChrisLedet see here: http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase. With the concern in place, you can `ActiveRecord::Base.send(:include, RollbackLogger)` to include in every model. – Damien Roche Oct 25 '13 at 21:38