2009-06-01 67 views
5

我在控制器内部有一个复杂的操作,它执行数据库的多个更新查询。Ruby On Rails的事务操作

如何在不进行任何结构重构的情况下使此行为像交易一样行事?

回答

6
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 

这里是the docs for the transaction method

4

这是更多钞票以使在控制器事务的所有操作一次:

around_filter :transactional 

def transactional 
    ActiveRecord::Base.transaction do 
    yield 
    end 
end 
+0

面向方面编程。 Ruby不能做什么? (除了在Windows上工作。) – Chloe 2013-04-02 16:46:30