轨道3 ActiveRecord的交易 [英] Rails 3 ActiveRecord Transactions

查看:93
本文介绍了轨道3 ActiveRecord的交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想从不同的控制器调用模型的方法。它看起来是这样的:

I have a model method that I'd like to call from various controllers. It looks something like this:

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!,这将回退任何错误?

In my controller, if I call @post.read!, will this rollback on any errors?

推荐答案

在当前设置,如果read_at给出了一个错误,它仍将继续到一个执行 thread.status <在code / code>例如。

In your current setup, if read_at gives an error, it will still continue onto the code that executes thread.status for example.

您想使用 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

通过使用交易,你可以放心,要么所有的数据库调用(在事务块内)将被保存到数据库中,或根本没有。

By using transactions, you can be assured that either all your database calls(within the transaction block) will be persisted to the database, or none at all.

这篇关于轨道3 ActiveRecord的交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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