Transaction Action with Ruby On Rails

I have a complex action inside the controller that executes several update requests to the database.

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

+5
source share
2 answers
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 .

+6
source

You can do all the actions in a controller transaction at the same time:

around_filter :transactional

def transactional
  ActiveRecord::Base.transaction do
    yield
  end
end
+4
source

All Articles