如果验证失败,请运行命令3

时间:2012-06-09 11:26:05

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 callback

我想运行这些命令:

require 'fileutils'
FileUtils.rm_rf Dir.glob("#{Rails.root}/public/uploads/tmp/*")

如果我的模型中的验证失败并带有回调:

我看过回调after_validation

如何通过after_validation回调检查验证是否正常或验证是否错误(KO)?

3 个答案:

答案 0 :(得分:2)

您可以查看

if your_model.errors.empty?
   # run commands
end

答案 1 :(得分:2)

class User < ActiveRecord::Base

  after_validation :do_something_if_validation_fails, :unless => lambda { errors.empty? }

  protected
  def do_something_if_validation_fails
    logger.info "Validation failed lets do something"
  end
end

答案 2 :(得分:0)

我的解决方案是:

after_validation :empty_tmp

  protected
  def empty_tmp
   if self.errors.any?
    require 'fileutils'
    FileUtils.rm_rf Dir.glob("#{Rails.root}/public/uploads/tmp/*")
   end
  end