This post covers getting started with Rails 4 and Mongodb, using the Mongoid gem. As part of getting up to speed, I enjoyed reading Rails + Mongo take on the object-relational mismatch by Emily Stolfo from MongoDB.

For starters, here’s a how to create a super simple toy app. I assume Ruby is installed via rvm, but you are new to Mongo.

Install Mongodb on Mac OSX

brew update
brew install mongodb

To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don’t want/need launchctl, you can just run:

Rails 4 with Mongoid

I chose Mongoid over MongoMapper (see quora, stackoverflow)
I used MRI 1.9.3 (at this writing, Mongoid supports HEAD but not 2.0)

rvm use ruby-1.9.3-p429@rails4 --create

added to Gemfile:

gem "mongoid", git: 'git://'

on the command-line:

rails new mongo-people --skip-active-record
rails generate mongoid:config
rails generate scaffold person name street city state
rails s

Woo hoo! We’ve got an app — looks like a vanilla Rails app from the outside, but it is different on the inside:

class Person
  include Mongoid::Document
  field :name, type: String
  field :street, type: String
  field :city, type: String
  field :state, type: String

No database migrations needed. If we want a new field, we could just declare one in the model and add it to our views. I assume migrations could be used for data migration, but that would be a subject of another post.


Rails 4 with MongoDB Tutorial

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>