Thursday, November 24, 2011

How to use MongoDB as model, session store and cache store on Rails3

When we use rails3 as out-of-the-box, we implicitly choose ActiveRecord for model, Cookie for session store and on-memory for cache store. But we can choose MongoDB for all of them. I start to explain these ways one by one.


MongoDB as model

There are two de-facto mapping libraries for MongoDB – the one is MongoMapper and the other one is Mongoid. In this article, I choose Mongoid. When we choose Mongoid on our rails3 application, we edit Gemfile like below:
gem 'bson_ext'
gem 'mongoid'

Then type commands like below:
> bundle update
> rails g mongoid:config

At last, edit config/mongoid.yml as you like. Then, you can create models for MongoDB.
> rails g model

If you still want to use ActiveRecord as model, you could type the command like below:
> rails g active_record:model
(You should check rails g -h for more details.)

MongoDB as session store

The library mongo_session_store supports both MongoMapper and Mongoid. In this article I introduce the way to use mongo_session_store with Mongoid. On our rails3 application, we edit Gemfile like below:
gem 'bson_ext'
gem 'mongoid'
gem 'mongo_session_store', require: 'mongo_session_store/mongoid'

Then type this command:
> bundle update

At last, edit config/initializers/session_store.rb like below:
Rails3Sample::Application.config.session_store :mongoid_store

If your mongo_session_store version is less equal than 2.0.0, you may fix the bug by your hand in lib/mongo_session_store/mongoid.rb on your gems path like below:
(Before)
def set_session(env, sid, session_data)
(After)
def set_session(env, sid, session_data, options=nil)

MongoDB as cache store

I choose mongo_store for my cache store library. When we use mongo_store on our rails3 application, we edit Gemfile like below:
gem 'mongo_store'

Then type this command:
> bundle update

At last, edit config/environments/production.rb like below:
config.cache_store = :mongo_store

(continuing to phosphorescence: Tips for MongoDB cache store and assets on Rails 3.1)

No comments:

Post a Comment