Ruby On Rails的事务操作

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

如何在不进行任何结构重构的情况下使此操作像事务一样

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