Skip to content

Instantly share code, notes, and snippets.

@raderj89
Last active May 13, 2020 07:46
Show Gist options
  • Save raderj89/f35b609616ce5d6a091fd7dfe7d015c7 to your computer and use it in GitHub Desktop.
Save raderj89/f35b609616ce5d6a091fd7dfe7d015c7 to your computer and use it in GitHub Desktop.
Make sessions queryable by user with ActiveRecord Session Store and Devise

Make sessions queryable by user with ActiveRecord Session Store and Devise

  1. Install the ActiveRecord Session Store gem and read the documentation for how to use it and create your sessions table.

  2. Create a migration to add user_id to the sessions 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
  1. 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
  1. Register the model with ActiveRecord Session Store in an initializer:
# config/initializers/active_record_session_store.rb

ActionDispatch::Session::ActiveRecordStore.session_class = CustomSession
  1. Now you can easily query sessions by user:
CustomSession.where(user_id: user.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment