Independant transaction

Hi there !

I am playing with nested transactions (Postgres) and have the aim to have a child transaction that is not rolled back if the parent transaction is.

I read about requires_new and at some other places (but strangely not in the docs) about joinable but in my test, none of these two options seem to do the trick.

Moreover, for my use case to be successful I should not modify the parent transaction (I have no control over it).

I make my tests in a rake task like this :

task doing_things: :environment do
  first_name = SecureRandom.uuid
  uuid = SecureRandom.uuid
  email = "#{uuid}@example.com"

  ActiveRecord::Base.transaction do
    Person.create!(first_name:)

    Operator.transaction(requires_new: true) do
      Operator.create!(email:, uuid:)
    end

    raise ActiveRecord::Rollback
  end

  puts Person.find_by(first_name:).inspect
  puts Operator.find_by(uuid:).inspect
end

In this example, I expect Person to be nil and Operator to be found. There are however both nil.

Does one of you already encountered a case like this and found a solution ?

Thanks for your time

Yours

1 Like