5

I have a complex action inside controller that performs several update queries to the database.

How can I make this action acts like transaction without any structural refactoring?

Bogdan Gusiev
  • 8,027
  • 16
  • 61
  • 81

2 Answers2

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

Here are the docs for the transaction method.

Sarah Mei
  • 18,154
  • 5
  • 45
  • 45
5

It's posible to make all actions in controller transactional at once with:

around_filter :transactional

def transactional
  ActiveRecord::Base.transaction do
    yield
  end
end
Bogdan Gusiev
  • 8,027
  • 16
  • 61
  • 81
  • Aspect-oriented programming. Is there nothing Ruby can't do? (Besides work on Windows.) – Chloe Apr 02 '13 at 16:46