Ryan Weald's Blog

Using Mongoid Alongside ActiveRecord

| Comments

MongoDB is a very popular document oriented database and more apps are using it every day. However, we all know about the problems that mongo has with data durability. So you might not want to use it as a complete replacment for ActiveRecord and your favorite sql store. Mongoid is an ActiveModel compliant ORM for MongoDB. Below I will outline how you can use Mongoid alongside ActiveRecord in your rails 3 app.

1) Add mongoid to your gemfile

1
2
  gem "mongoid", "~> 2.0"
  gem "bson_ext", "~> 1.3"

2) Run the mongoid generator in your projects root directory

1
rails generate mongoid:config

This will generate a config/mongoid.yml file where you can configure your connection to mongodb.

3) Right now mongoid has overriden activerecord as the default orm so any attempts to generate migrations or ActiveRecord models will fail. Therefore we must configure our default generators so we can still use activerecord.

To do that simple add the following line to your config/application.rb file

1
2
3
  config.generators do |g|
    g.orm :active_record
  end