在after_save回调中返回false并回滚 [英] Return false and rollback in after_save callback

查看:79
本文介绍了在after_save回调中返回false并回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ActiveRecord模型after_save回调中,我需要ROLLBACK事务并返回false。

In ActiveRecord model after_save callback I need to ROLLBACK transaction and return false.

def after_save_callback
  if mycondition?
    raise ActiveRecord::Rollback
  end
end

此回调回滚事务,但是mymodel.save!返回true。

This callback rolls-back transaction but mymodel.save! returns true. How to make it return false and rollback?

推荐答案

我不认为您可以使用做到这一点。 after_save 您应该查看 around_save

I don't think you can do this with after_save You should be looking at around_save instead:

def around_save
  ActiveRecord::Base.transaction do
    yield # calls the actual save method
    raise ActiveRecord::Rollback if my_condition?
  end
end

这篇关于在after_save回调中返回false并回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆