Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails transactions within transactions?

What happens when you have transactions with transactions

def a
  ActiveRecord::Base.transaction do
    # stuff
  end
end

ActiveRecord::Base.transaction do
  a
  # more stuff
end

What happens if the inner transaction succeeds but the outer fails and vice versa? What happens when both succeed or fail?

like image 712
Derek Avatar asked Nov 19 '13 02:11

Derek


People also ask

How do rails transactions work?

For example, when you use a transaction in Rails, it ties up one of your DB connections until all the code in your transaction block finishes running. If the block contains something slow, like an API call, you could tie up a DB connection for an unreasonable amount of time.

What are custom transactions in rails?

Rails transactions are a way to ensure that a set of database operations will only occur if all of them succeed. Otherwise they will rollback to the previous state of data.

What does ActiveRecord base do?

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


1 Answers

transaction calls can be nested. By default, this makes all database statements in the nested transaction block become part of the parent transaction.

The behaviour is well described in the documentation

like image 55
mechanicalfish Avatar answered Oct 03 '22 21:10

mechanicalfish