User.transaction do
  User.create(username: 'Kotori')
  User.transaction do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end

In this example, both users were created. This is why the nested transaction is part of the parent transaction and the ActiveRecord::Rollback is captured in the transactions, so the parent transaction doesn't receive the exception.

User.transaction do
  User.create(username: 'Kotori')
  User.transaction(requires_new: true) do
    User.create(username: 'Nemu')
    raise ActiveRecord::Rollback
  end
end

In the second example the sub-transaction has the requires_new: true. This indicates that the sub-transaction is a real transaction, and it will perform a rollback. Only the Kotori user is created.

User.transaction do
  User.create(login: 'Kotori', password: 'Nemu')
  User.transaction do
    User.create(login: 'Nemu', password: 'Kotori')
    raise ActiveRecord::RecordInvalid
  end
end

Finally, in this example we have another type of exception, so it is not captured by the transaction and none user is created.


📌 API Ruby on Rails: transaction method

📌 API Ruby on Rails: Transactions