MongoDB with ROR

In terminal.

1.Create new application.

type ‘rails new <insert app name here>’

2. Add mongoid gem to file

gem ‘mongoid’, ‘~>5.0.0’

3. Configure mongo database.

type ‘rails g mongoid:config ‘ in terminal

creates a yml file. within the file there is the name of the database created, <app name>_development.

All these steps helps to create a connection to the database when the application is start up.

4. Open the application.rb file in config directory,  you need to add  a line that is “Mongoid.load!(‘./config/mongoid.yml’)” which basically bootstraps the mongoid to the application, connect to the database and we can access data that we need as part of the MVC application.

5. Import data(for application named zips)

type ‘mongoimport –db zips_development –collection zips –file ~/downloads/zips.json’ in terminal

6. open up two terminals. For one, type in rails s and another one type in rails c

7. In rails c terminal, type in mongo_client=Mongoid::Clients.default

to create a mongo client object.

Play around with it. For example, typing mongo_client.database.name gives the name of the database which is zips_development.

8. Instantiate a collection object

collection=mongo_client[:zips]

then type in collection.count, where you can see the number of objects.

9. Next up DAO(data access object) model class infrastructure which connects the view to the controller.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s