Showing posts with label Stepwise setup rails 5 with Mongoid gem. Show all posts
Showing posts with label Stepwise setup rails 5 with Mongoid gem. Show all posts

Thursday 21 September 2017

Stepwise setup rails 5 with Mongoid gem

Stepwise setup rails 5 with Mongoid gem

In this tutorial we will discuss about how to setting up Rails 5 with MongoDB and MongoID.

Prerequisite: MongoDB must install in your local system.
To check installation of MongoDB, type http://localhost:27017/ on your browser, if you receive below message than you are good to go. 

Stepwise setup rails 5 with Mongoid gem


Step 1: Create your Rails app with the '--skip-active-record' switch.

rails new mongopoc --skip-active-record
Stepwise setup rails 5 with Mongoid gem



You will get directory structure.

The --skip-active-record is important because it doesn't include ActiveRecord in the app that is generated.

Step 2: Edit the gemfile  and add below gem to include mongodb.
gem 'mongo','~>2.4.1'
gem 'mongoid','~>6.1.1'

Stepwise setup rails 5 with Mongoid gem

Step 3: Run a command bundle install --local to install the gem in your app.

Go to your rails project path using cmd and run bundle install --local

bundle install --local
Stepwise setup rails 5 with Mongoid gem
 

Run command gem list and check mongo and mongoid in list.

gem list
Stepwise setup rails 5 with Mongoid gem
Step 4: Configure your app to support mongo db

rails g mongoid:config
Stepwise setup rails 5 with Mongoid gem

Check your 'application.rb' file and make sure that inside the 'class Application' there is the line " Mongoid.load! './config/mongoid.yml' ". It's sometimes not included when the config is generated, but it's needed to use Mongoid.

Step 5: Create a new model with attributes.

rails g scaffold employee name:String age:Integer
Stepwise setup rails 5 with Mongoid gem

Step 6: Delete //= require_tree from application.js 

Stepwise setup rails 5 with Mongoid gem


Step 7: Start server and insert values

rails sever 

Stepwise setup rails 5 with Mongoid gem

**Make sure your mongoDB is up and running. You can check URL in routes.rb. In our case it is employees so we will hit http://localhost:3000/employees and insert some values.

Stepwise setup rails 5 with Mongoid gem
Step 8: Check database for the inserted values.

show dbs;
Stepwise setup rails 5 with Mongoid gem

use mongopoc_development;
Stepwise setup rails 5 with Mongoid gem

show collections;
Stepwise setup rails 5 with Mongoid gem

db.employees.find();
Stepwise setup rails 5 with Mongoid gem



Related Post: