Setup Ruby on Rails 6 App with MongoDB under 5 Minutes

Setup Ruby on Rails 6 App with MongoDB under 5 Minutes

Rails 6 App with MongoDB

In this article, I will be discussing how to quickly setup a NoSQL database MongoDB with your brand new Rails 6 app. I am using Ubuntu 14.04Ruby 2.5.1 and Rails 5.2 for this tutorial.

MongoDB is an open source database management system (DBMS) that uses a document-oriented database model which supports various forms of data.

If you have not installed MongoDB on your system you first need to install it. Here are the steps for Ubuntu 18.04 LTS .

$ wget -qO - | sudo apt-key add -
$ echo "deb [ arch=amd64 ] bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

$ sudo apt-get update
$ sudo apt-get install -y mongodb-org

After finishing the setup, start the MongoDB server. Here are some essential commands for that.

To interact with MongoDB usedollowing command, each has it own corresponding task as mentioned:

$ sudo service mongod start
$ sudo service mongod stop
$ sudo service mongod restart

Setting Rails App

Create a new rails application. Make sure that you add –skip-active-record.

$ rails _6.0.0_ new mongodb_rails_demo --skip-active-record

If you notice, The database.yml is not added automatically. Now we have to add two gems which will be a bridge for us between Rails and MongoDB.

Add the following gems to your Gemfile.

gem 'mongoid'
gem 'bson_ext'

Now do bundle install. Now we have to generate a configuration file for hooking mongod adapter with MongoDB. It will be similar to database.yml file. Run the following command in order to generate MongoDB configuration files.

rails g mongoid:config

It will create  mongoid.yml under config directory, we need to update it based on our MongoDB configurations and create a database with rake db:create.

To add a model you can use scaffold.

rails g scaffold post title:string detail:text

This will generate all necessary files as we usually have in usual scaffolding. The major difference you will notice is that Mongoid has automatically added a module include Mongoid::Document in that model.

class Post
  include Mongoid::Document
  field :title, type: String
  field :detail, type: String

The long you stick with mongod, all of those basic Active Record methods and commands will work here too. Now you Rails 6 app is ready to use with MongoDB.


Model Preloading: Mongoid needs to pre-load all models before every request in development mode in order to properly set up single collection inheritance. This can get slow that’s why if you are not using any inheritance it is recommended you turn this feature off.

config.mongoid.preload_models = false

Reference from documentation for setting up Rails 6 App with MongoDB: visit this page.

Leave a Reply