Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4, better logging on rollback?

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?

like image 406
James McMahon Avatar asked Oct 25 '13 20:10

James McMahon


Video Answer


1 Answers

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.

like image 65
Chris Ledet Avatar answered Oct 11 '22 09:10

Chris Ledet