2009-06-01 72 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