Using permanent_records Gem with ActiveRecord Session Store

I spent a couple hours pulling out hair when, after switching my Rails app from using the Cookie session store to the ActiveRecord session store, I could no longer log in without an arcane exception RecordNotSaved.

Searches on the web revealed no correlation between using the ActiveRecord session store with the permanent_records gem but stepping through the libraries with pry strongly suggested that calls to loaded? in a couple of Session callbacks should have returned true but didn’t because the record had been deleted thanks to permanent_record.

In the end the following quick monkey patch was all that was needed. Place this in config/initializers/session.rb and enjoy.