boldr by Nicolas Mérouze

Store Rails sessions in MongoDB

There are a few built-in session stores in Rails but if you want to store them in MongoDB (or anything not using ActiveRecord) there's nothing. Not anymore with mongo_session_store!

NOTE: The project was initially created by Chris Brickley with MongoMapper support but without Mongoid support and it was not in a gem.

Usage with MongoMapper

First we load the gem:

config.gem "mongoid"
config.gem "mongo_session_store"

Don't forget to create an initializer to add the connection to the database. Then configure Rails to use MongoMapper for sessions (in the session store initializer):

config.gem "mongo_mapper"
config.gem "mongo_session_store", :lib => "mongo_session_store/mongo_mapper"

Usage with Mongoid

It's almost the same with Mongoid. First setup the environment correctly:

require "mongo_session_store/mongoid"
ActionController::Base.session_store = :mongoid_store

Then the session store initializer:

ActionController::Base.session_store = :mongo_mapper_store

NOTE: Mongoid acts a bit differently than MongoMapper but I havn't had the time to fix the issue.


I'm gonna add some tests, try to have the same usage for Mongoid and MongoMapper and add Rails 3 support. But if you want some other things please fork it.

If you liked the article and/or want to talk to me about it, you can follow me on twitter.