arongka
arongka

Reputation: 451

Which file to modify when using mongodb ruby driver to connect rails API application with mongodb

I am following this tutorial to make a rails RESTful API application:

https://scotch.io/tutorials/build-a-restful-json-api-with-rails-5-part-one

But I want to use mongodb database instead of sqlite. So I created the application by running this command:

rails new Research_and_Publications --api -T --skip-active-record

Then, to connect with mongodb, I am following this link:

https://docs.mongodb.com/ruby-driver/master/quick-start/

But I cannot get where to put this piece of code:

require 'mongo'
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
db = client.database

db.collections # returns a list of collection objects
db.collection_names # returns a list of collection names`

Please help me in which file should I add this code.

Upvotes: 2

Views: 76

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53038

mongoid is the official Object Document Mapper framework for MongoDB in Ruby. I would suggest you to use that in your application.

Add mongoid gem in your Gemfile as below:

gem 'mongoid', '~> 6.1.0'

and run bundle install

Next, generate the config file your_app/config/mongoid.yml by running the following command:

rails g mongoid:config

And you are all set. Follow the tutorials on mongoDB site to help you further set up models, configuration, etc.

Upvotes: 2

Related Questions