A real `with_connection`?

I often need to do some independent ActiveRecord work while in the middle of some other work. For example, I’m in the middle of a DB transaction processing a request or a job when I need to immediately deactivate a user. The change to the user won’t be visible until the end of the transaction, or it may even be aborted later down the line due to an error. Therefore I need to open a fresh connection and do my work there, immediately.

ActiveRecord keeps the current connection in ambient (IsolatedExecutionState, either thread-local or fiber-local). What I need is a way to checkout a connection and make that connection the ambient one. The existing with_connection seems like it should fit, but unfortunately it doesn’t do that - if an ambient connection exists it will simply yield that one. I know I can use checkout to checkout a real new connection, but I can’t make that connection the ambient one to use with ActiveRecord, I can only execute raw SQL with it.

Ideally:

# ambient connection 1 here...
MyRecord.real_with_connection do
  # ambient connection 2 here...
  MyRecord.create!(...)
end
# ambient connection 1 here again

Is there a way to achieve this in current Rails? Can I somehow make the manually-checkout connection the ambient one?

1 Like