-
Install the ActiveRecord Session Store gem and read the documentation for how to use it and create your
sessions
table. -
Create a migration to add
user_id
to thesessions
table.
class AddUserIdToSessions < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_column :sessions, :user_id, :integer
add_index :sessions, :user_id, algorithm: :concurrently
end
end
- Create a Session model:
# app/models/custom_session.rb
class CustomSession < ActiveRecord::SessionStore::Session
before_save :set_user_id
private
def set_user_id
if data['warden.user.user.key'].present?
self.user_id = data['warden.user.user.key'].first.first
end
end
end
- Register the model with ActiveRecord Session Store in an initializer:
# config/initializers/active_record_session_store.rb
ActionDispatch::Session::ActiveRecordStore.session_class = CustomSession
- Now you can easily query sessions by user:
CustomSession.where(user_id: user.id)