This a tutorial to help you setup MongoDB as the database for Rails. Let’s start with a bit of info on MongoDB.
What is MongoDB?
So what is a NoSQL database? What’s difference between a NoSQL database (MongoDB) and SQL database (MySQL, PostgreSQL and etc.)?
There are lots of technical differences, but I’ll talk about two key areas: structure and scaling.
NoSQL database allow free-flow operations, however SQL/Relational databases require a structure with defined attributes to hold the data
Both NoSQL and SQL can scale. However, SQL databases were built to scale vertically (increase system resources like adding CPUs or memory to a single computer). NoSQL was built for scaling horizontally (i.e. by creating a cluster of multiple machines; think cloud!).
Now let’s start setting MongoDB up.
We will be using mongoid as the ORM for your Rails application. On your Gemfile, add the following:
Make sure to remove sqlite gem to avoid conflict.
Next step is to tel Rails that you will be using mongoid instead of active_record. On your application.rb file, remove the this line:
And replace it with these lines:
require "active_model/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" require "rails/test_unit/railtie"
Remove the following code that still uses active_record.
config.active_record.migration_error = :page_load
config.active_record.dump_schema_after_migration = false
config.active_record.raise_in_transactional_callbacks = true
You can checkout my demo repo for this tutorial: https://github.com/iamademar/mongoid_rails_demo
This is the specific commit on adding mongoid: https://github.com/iamademar/mongoidrailsdemo/commit/9f3fb594ca17d954aefa29092246f1977f360ddf