18
How to Set up Rails MongoDB App in 10 minutes
“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
/etc/apt/sources.list.d/mongodb-org-3.6.list
$ 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'
gem 'bson_ext'
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.
That’s it. Your Rails application is ready for use with MongoDB. For more details regarding Ruby mongo gem visit, this page If you want to get more Rails specific details, then visit this page.
18