using the activerecord session_store for session tracking

Here’s what you need to do to take advantage of AR’s SessionStore. The following was tested with Rails 3.2.5.

    1. Run rake db:sessions:create
    2. Run rake db:migrate
    3. Modify config/initializers/session_store.rb to this:
       YourApp.config.session_store :active_record_store


  • Add the following in application.rb:
     config.action_dispatch.session_store = :active_record_store  


This will setup the default session tracking mechanism. I wanted to have a custom Session class, which held the user_id ( if he’s logged in ). Here’s the additional things I’ve done:

    1. I added in config/initializers/session_store.rb the following line:
       ActiveRecord::SessionStore.session_class = Session


  • I added the following code in app/models/session.rb :
    class Session < ActiveRecord::SessionStore::Session 
      belongs_to :user 
      before_save :ensure_user_is_set 
      def self.find_by_session_id(session_id) 
        find(:first,:conditions => ["session_id = ?",session_id]) 
      def ensure_user_is_set 
        warden_data = self.data["warden.user.user.key"] 
        if warden_data 
          user_id = warden_data[1][0] 
          self.user = User.find(user_id) 




2 Responses to “using the activerecord session_store for session tracking”

  1. August 5, 2012 at 14:27

    Could you provide an example on how to access the user from the session please? I’m getting an exception NoMethodError Exception: undefined method `user’ for #. This is obviously because the session object in rails is a rack session hash – how do we access our activerecord session object?

    • August 9, 2012 at 14:49

      You could do:


      and you’d get the actual ActiveRecord session object. I have a feeling that calling session directly returns you the actual session data from the activerecord object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog Stats

  • 238,127 hits

%d bloggers like this: