Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

342
Visualizações
How ActiveRecord::Rollback behaves in nested begin-rescue blocks

I have below code

ActiveRecord::Base.transaction do
  begin
    account.save
    # outer statement
    begin
      user.save
      # inner statement
    rescue StandardError
      raise ActiveRecord::Rollback
    end
  rescue StandardError
    raise ActiveRecord::Rollback
  end
end

If there is an exception in 'inner statement', only 'user' will be rollbacked, right? 'account' won't be rollbacked in that case, isn't it?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In your code there is a single database transaction, and it is all-or-nothing. Rolling back a transaction will roll back all the changes made in that transaction, regardless of where you issue the rollback.

You can nest transactions as well, but be wary that by default transactions are squished together, so even if you add a second transaction inside first transaction:

ActiveRecord::Base.transaction do
  begin
    account.save
    # outer statement
    ActiveRecord::Base.transaction do
      begin
        user.save
        # inner statement
      rescue StandardError
        raise ActiveRecord::Rollback
      end
    end
  rescue StandardError
    raise ActiveRecord::Rollback
  end
end

This will still result in the single transaction, and rollback will cancel all the changes.

To ask for a real subtransaction, you need to add request_new: true to the inner transaction:

ActiveRecord::Base.transaction do
  begin
    account.save
    # outer statement
    ActiveRecord::Base.transaction(require_new: true) do
      begin
        user.save
        # inner statement
      rescue StandardError
        raise ActiveRecord::Rollback
      end
    end
  rescue StandardError
    raise ActiveRecord::Rollback
  end
end

However, at the moment the only database supporting true nested transaction is MS-SQL. Rails at the moment handles this using save points - so don't be confused by the logs.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda