Rails 3 ActiveRecord交易

我有一个模型方法,我想从各种控制器调用。 它看起来像这样:

def Post < ActiveRecord::Base def read! self.read_at = Time.now self.save self.thread.status = Status.find_by_name("read") self.thread.save end end 

在我的控制器中,如果我打电话给@post.read! ,这会回滚任何错误吗?

在当前的设置中,如果read_at给出错误,它仍将继续执行执行thread.status的代码。

您想使用ActiveRecord事务 :

 def read! transaction do self.read_at = Time.now self.save self.thread.status = Status.find_by_name("read") self.thread.save end end 

通过使用事务,您可以确保所有数据库调用(在事务块中)都将持久保存到数据库,或者根本不存在。