The first step to learning Ruby on Rails is to setup your development environment.
Get started →
Learn the ins and outs of Ruby on Rails development through our podcasts.
Browse topics →
If you've never checked out MongoDB before, I'd very much encourage you to. It's a NoSQL document store that makes for a very interesting method of development compared to relational databases. We've been using it a lot lately for prototyping at Efeqdev and have thoroughly enjoyed it. Today we're going to walk through installing it on Ubuntu and setting up Rails with MongoDB and Mongoid to replace ActiveRecord.
First let's install MongoDB from their official repository:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 sudo echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list sudo apt-get -y update sudo apt-get -y install mongodb-10gen
If you run
mongo in your shell you should get an interactive database prompt:
MongoDB shell version: 2.4.6 connecting to: test >
Next you're going to need to generate your Rails application with
rails new myapp. We need to modify the Gemfile to remove sqlite3 and add Mongoid.
You'll want to delete these lines from your
# Use sqlite3 as the database for Active Record gem 'sqlite3'
And add these:
gem 'mongoid', '~> 4', github: 'mongoid/mongoid' gem 'bson_ext'
The mongoid gem that supports Rails 4 hasn't been fully published yet so we're using it directly from their Github repository. Now that these are added you can run
bundle to install the gems for your Rails app.
Now we need to generate the Mongoid configuration file that is very much like your
config/database.yml that you may be used to with ActiveRecord. We'll create the mongoid file by running the following command:
rails g mongoid:config
config/mongoid.yml which you can take a look at and make any configuration changes as necessary.
Last but not least, we need to remove ActiveRecord from loading by default with Rails. To do this we need to edit
Delete the line that says
require 'rails/all' and add these 3 lines:
require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie"
One last place to remove an ActiveRecord reference is the
config/environments/development.rb file which tells ActiveRecord to display migration errors. Since Mongo doesn't have structured tables like a relational database we need to get rid of this. Just delete this line in the file:
config.active_record.migration_error = :page_load
And that's all there is to it! While it's much more work than you might expect, I imagine this will become a smoother process in the future once the Rails 4 gem has been released. Be sure to check out Mongoid's documentation for more information on how to use it.
GoRails is a blog and screencast series deciated to teaching developers how to build web applications.