How I can log to a file validation errors of models ?
I want to have a custom log file, where validation errors are logged when I play in development mode with my application.
What is the best option to achieve that ?
Is monkey patching of the save method a good idea ? Or have You some better 开发者_StackOverflow社区way to do that ?
Depends on what you want to do but how about something like this:
# model
after_validation :log_errors, :if => Proc.new {|m| m.errors}
def log_errors
Rails.logger.debug self.errors.full_messages.join("\n")
end
I've combined both of Lenart and Altonymous suggestions. So we make a concern (since Rails 4)
# app/models/concerns/log_validation_errors.rb
module LogValidationErrors
extend ActiveSupport::Concern
included do
after_validation :log_errors, if: proc { |m| m.errors }
end
def log_errors
Rails.logger.debug "Validation failed!\n" + errors.full_messages.map { |i| " - #{i}" }.join("\n")
end
end
and change our models to include it
# app/models/my_model.rb
class MyModel < ApplicationRecord
include LogValidationErrors
# ...
end
I know this is old... but for others. I created a module that I include in my models.
# validation_logger.rb
module ValidationLogger
def self.included(base)
base.send :include, InstanceMethods
base.after_validation :log_errors, if: ->(m) { m.errors.present? }
end
module InstanceMethods
def log_errors
Rails.logger.warn "#{self.class.name} #{self.id || '(new)'} is invalid: #{self.errors.full_messages.inspect}"
end
end
end
I would write a before_save callback and log the errors if valid? returns false.
精彩评论