Here’s what you need to do to take advantage of AR’s SessionStore. The following was tested with Rails 3.2.5.
- Run rake db:sessions:create
- Run rake db:migrate
- 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:
- 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]) end private 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) end end end