Search code examples
ruby-on-railsrubysessionactiverecordrubygems

Rails 7 ActiveRecord::SessionStore - how to get database id of current session in the controller?


I'm using Rails 7.1.3.2 and have just installed activerecord-session_store (2.1.0).

https://github.com/rails/activerecord-session_store

It's all working - session values i set in the controller get saved into the Session record in the database. However, I also want to set an account_id field in the Session record in the database, so I can get the most recent Session record for an Account record, in my test script.

How can I actually set that? I can't work out how to get at the session model record in the controller.

In the documentation (link above) it says "However, you must set session.model.id = session.session_id by hand! A before filter on ApplicationController is a good place."

But if I call session.model in the controller I get this exception:

undefined method `model' for an instance of ActionDispatch::Request::Session

If I call session.id then I get an alphanumeric string, which is the value of the session cookie, but it's different to the value stored in the id field and the session_id field, in the database.

All I actually need to do is get the database id of the current session record, then I could update the account_id field with an sql query. Does anyone know how i can access the actual model record?


Solution

  • Looking at the code I don't see when session.model was ever a thing you could do, maybe when this gem was part of Rails v3. Best I figured out is to use session model directly:

    ActiveRecord::SessionStore::Session.find_by_session_id(session.id.private_id)
    

    Also this bit caught my eye:

    request.env[SESSION_RECORD_KEY] = session
    

    You have to load the session before env is populated though:

    session.send(:load!)
    model = request.env["rack.session.record"]