Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top