Using MongoMapper with Rails 3 and 4 is easier than ever. Thanks to new features in ActiveSupport, and the new ActiveModel framework (which MongoMapper 0.9+ uses), your app can be up and running on MongoDB in a matter of seconds.
First, if you’re generating a new Rails application, it is recommended to leave out the ActiveRecord dependencies (unless you need them of course). From the console, just run:
But, not everyone is starting fresh. Andy Lindeman has an eBook about upgrading from Rails 3 to Rails 4. If you’re not upgrading, but just converting an existing Rails application from ActiveRecord (or another ORM), simply open
config/application.rb and replace:
With (for Rails 3):
Or (for Rails 4):
Next, add MongoMapper to your
Gemfile, and run
Now, you’re almost ready to go, but you still need some configuration info. Generate
config/mongo.yml by running:
If you want to configure your application with a MongoDB URI (i.e. on Heroku), then you can use the following settings for your production environment:
Technically, you can initialize MongoMapper and use it to store data now. However, I like to configure Rails’ model generator. Inside of the Application class (
config/application.rb) I add:
One other small note, make sure any ActiveRecord related configuration items are commented out or removed like below:
This will allow you to use the
rails generate model command with MongoMapper.
You’re now finished, go forth and create!
Generate a user model with
bundle exec rails g model user name:string:
Create a user with
bundle exec rails c: