Ruby on rails Rails-在observer中添加验证

Ruby on rails Rails-在observer中添加验证,ruby-on-rails,validation,ruby-on-rails-4,activerecord,Ruby On Rails,Validation,Ruby On Rails 4,Activerecord,嗨,我的模型上有状态机,我需要在observer上添加验证。当我试着 def before_transition(record, transition) to = transition.to.to_s record.errors.add(:state, "Can't cancel") if to == 'cancel' return false end 当我用更好的错误和调用方gem的绑定来调试它时,我可以看到错误添加到记录中 >> record.errors.any?

嗨,我的模型上有状态机,我需要在observer上添加验证。当我试着

def before_transition(record, transition)
  to = transition.to.to_s
  record.errors.add(:state, "Can't cancel") if to == 'cancel'
  return false
end
当我用更好的错误和调用方gem的绑定来调试它时,我可以看到错误添加到记录中

>> record.errors.any?
=> true
但它正在保存记录

如果我在observer中添加before_update方法。在转换方法之后运行

def before_update(record)
  >> record.errors.any?
  => false       
end
错误消失了

我如何取消观察员中某些条件下的更新过程


PS:我不能用validate方法在模型中进行转换,因为我不能用custom validator方法进行转换。

我不知道这样做是否正确,但我用

raise ActiveRecord::Rollback, "There is an error"
我以前是

def before_transition(record, transition)
  to = transition.to.to_s
  record.errors.add(:state, "Can't cancel") if to == 'cancel'
  if record.errors.any?
    raise ActiveRecord::Rollback, "There is an error"
  end
end