Thursday, July 6, 2017

Using MongoDB With Ruby On Rails 5

In this post I am going to walk you through installing Ruby on Rails 5 using rbenv and use the Mongoid MongoDB driver for Ruby. MongoDB is a fantastic NoSQL database that is incredibly scalable and fast which makes a good combo with Rails. We will be using Linux Ubuntu 16.04 with MongoDB and Rails already installed.

Create a Rails App (Without Active Record)

rails new myapp --skip-active-record
Using the –skip-active-record option will create the app without the database.yml config file. We will use a mongoid config file instead. This will also prevent using the sqlite gem. We will add the Mongoid gem below

Edit Gemfile

Add the following to your Gemfile
gem 'mongoid', '~> 5.1.0'

Generate Mongoid Config File

rails g mongoid:config
This will create config/mongoid.yml
Thats It! you should now be able to run “rails s” and use MongoDB
rails g scaffold post title body author created
Now visit “http://localhost:3000/posts” and you should have CRUD functionality using MongoDB

If you did NOT use the “–skip-active-record”

Remove Gem “sqlite” from the Gemfile
Delete the database.yml file
Go to config/application.rb and remove “require rails/all” and replace with…

require "action_controller/railtie"
require "action_mailer/railtie"
require "rails/test_unit/railtie"
Comment out any line that has “active_record” in it in the following files
/config/development.rb
/config/production.rb
/config/initializers/new_framework_defaults.rb

1 comment:

  1. It is nice blog Thank you provide important information and i am searching for same information to save my time Ruby on Rails Online Training

    ReplyDelete