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!
,这会在出现任何错误时回滚吗?
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
In my controller, if I call @post.read!
, will this rollback on any errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您当前的设置中,如果 read_at 给出错误,它仍然会继续执行例如执行
thread.status
的代码。你想使用ActiveRecord事务:
通过使用事务,你可以放心您的所有数据库调用(在事务块内)将被持久化到数据库,或者根本不会。
In your current setup, if read_at gives an error, it will still continue onto the code that executes
thread.status
for example.You want to use ActiveRecord transactions:
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.