How to Set up Rails MongoDB App in 10 minutes (Updated)
“MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.”
In this article, I am going to show you how to setup schema-less database MongoDB with your Rails 5 application. I am using Ubuntu 14.04, Ruby 2.5.1 and Rails 5.2 for this tutorial.
If you have not installed Ruby on Rails MongoDB on your machine, then you first need to install it. Here are the steps.
$ sudo apt-key adv - keyserver hkp://keyserver.ubuntu.com:80 - recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
$ echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse" | sudo tee
$ sudo apt-get update
$ sudo apt-get install -y mongodb-org
I have Ubuntu 14 but if you are using older or newer version then these steps may vary. You can find more details to install Rails MongoDB for these versions here.
Read More: How to install and use MongoDB with Rails 6
Once you finish the setup, start the MongoDB server. Here are some additional commands for that. To set up MongoDB:
To start MongoDB use:
$ sudo service mongod start
To stop MongoDB use:
$ sudo service mongod stop
To restart MongoDB use:
$ sudo service mongod restart
Let’s move to the Rails part now!
Create a new rails application to use Ruby MongoDB. Make sure that you add –skip-active-record.
$ rails new my_mongo_app --skip-active-record
If you notice, there is no database.yml and no sqlite3 gem is 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 Gemfile.
gem 'mongoid', '~> 6.0'
Now do bundle install. Now we have to generate mongoid.yml file which is similar to database.yml file for us.
Run the following command to generate MongoDB configuration files.
rails g mongoid:config
Now update mongoid.yml file based on your MongoDB configurations and create a database with rake db:create Mongoid provides these generators to manage database with these rake tasks.
To add a model you can use scaffold and Mongoid will automatically add a module include Mongoid::Document in that class. Here’s the Rails scaffold example and code:
rails g scaffold article name:string content:text
This will generate all files as we usually have in normal scaffolding and you can access it from /articles.
Ruby on Rails Case Studies
At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management