Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction Action with Ruby On Rails

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?

like image 314
Bogdan Gusiev Avatar asked Jun 01 '09 05:06

Bogdan Gusiev


People also ask

What is transaction in Ruby on Rails?

What Is A Transaction? Transactions are typically used when you need to ensure data integrity, even if your web app crashes in the middle of a request. Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.

How do rails transactions work?

Rails transactions are tied to one database connectionAnd as long as the transaction block is running this one database connection is open. So try to do as little as needed inside the transaction block, otherwise you will be blocking a database connection for more time than you should.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

How do you destroy in rails?

To create the controller action for the destroy-resource, we perform three substeps: (1) create an empty destroy-resource controller action, (2) add code to the action that retrieves the model object, and (3) add code to the action that destroys the model object and responds to the browser with an HTTP redirect.


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.

like image 53
Sarah Mei Avatar answered Oct 05 '22 23:10

Sarah Mei


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
like image 34
Bogdan Gusiev Avatar answered Oct 05 '22 23:10

Bogdan Gusiev