我有内部控制器,其执行几个更新查询到数据库的复杂的动作。

如何能做出这个动作的就像交易的没有任何结构性重构?

有帮助吗?

解决方案

MyModel.transaction do
  begin
    @model.update_stuff
    @sub_model.update_stuff
    @sub_sub_model.update_stuff
  rescue ActiveRecord::StatementInvalid # or whatever 
    # rollback is automatic, but if you want to do something additional, 
    # add it here
  end
end

下面是的文档的交易方法

其他提示

这有可能使在控制事务的所有操作在同一次:

around_filter :transactional

def transactional
  ActiveRecord::Base.transaction do
    yield
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top