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
通过使用事务,您可以确保所有数据库调用(在事务块中)都将持久保存到数据库,或者根本不存在。
- validation以确保唯一但忽略空值?
- Ruby on Rails – STI的替代品?
- ActiveRecord有两个关联
- Rails – 在ActiveRecord中在运行时添加自定义字段
- 如何在Postgres中进行查询以按月创建分组记录? (:created_at datetime列)
- Rails模型validation条件allow_nil?
- 与核心的find_by()和FinderMethods的有什么区别?
- 为什么accept_nested_attributes_for allow_destroy不起作用?
- 从范围记录计算总数百分比并显示虚拟属性(Rails / Active Record)