Getting Started with MongoDB Atlas and Ruby on Rails
Rate this tutorial
The funny thing is, though, I am not a Ruby developer, let alone a Ruby on Rails developer. Thankfully, this was a well organized event with tutorials to follow, and plenty of coaches if any of us got stuck. So as well as chatting to attendees about MongoDB, I had the chance to follow along and learn something new.
At first, I followed along with the Rails Girls App Tutorial and got up and running with a working Ruby on Rails application. But this uses SQLite (I know, booooo), so I decided to take what I had learned, combined with our own documentation for getting started with Rails, and create a Rails app
that allows you to use MongoDB Atlas instead!
I am forever thinking of new ideas for content or side projects. My brain is buzzing constantly and finds inspiration in many places. So I loved the idea from the Rails Girls tutorial of a website that allows you to store an idea, including the name, description, and a picture to show what sparked that idea.
In this article, I will talk you through what I learned along the way creating this, and how you can make the same thing yourself! If you would rather browse code, it is publicly available on GitHub.
You will need to have a few tools in place in order to follow through this article:
- Free MongoDB Atlas Cluster — this will guide you through creating your first cluster and getting your all-important connection string that will be used in this tutorial.
The first step is to create the application. We can take advantage of the rails cli tool that is part of the Rails installation to bootstrap our new application.
1 rails new inspiration --skip-active-record --skip-bundle 2 cd inspiration
We pass the
--skip-active-record
option because we won’t be using an ActiveRecord adapter to communicate with our MongoDB database. We also pass -–skip-bundle
because we want to modify the application’s Gemfile
to include the mongoid
gem first before installing the bundle.Now we have the project created, we want to configure MongoDB. The first step is to add the mongoid gem. Mongoid is the officially supported object document mapper (ODM) for Ruby. An ODM is the document database equivalent of object relational mapper (ORM) which is used to map between models and the relational database.
- Inside your Gemfile, add
gem mongoid
, which defines that we want to use this gem. - From your CLI, run
bundle install
to pull down the required files to include mongoid in your application. - Once complete, run the command
rails g mongoid:config
, which will generate the mongoid.yml file inside your application’s config directory. This configuration file defines how to connect to your MongoDB database. - Update the development config section inside
config/mongoid.yml
with the following code, replacing the uri section with your own connection string:
1 development: 2 clients: 3 default: 4 uri: mongodb+srv:/<username>:<password>@<cluster url>/?retryWrites=true&w=majority 5 options: 6 server_selection_timeout: 5 7
Now we have our connection string added, we will be able to store our ideas documents inside MongoDB Atas.
We then want to run the application to make sure everything is working correctly.
1 rails server
This will start a server at https://localhost:3000, so open this in your browser of choice and make sure that the page loads. Out of the box, you get a Ruby on Rails logo.
Ruby on Rails uses the Model-View-Controller architecture. This means that we will have an
Idea
model that represents the document we want to store, a view to display that idea in the front end of our application, and a controller that allows us to interact with our ideas.Thankfully, creating all this is really simple. Within the Rails cli, you can run a command that will scaffold out everything we need, including our model with the properties we specify, the view, and the controller.
1 rails generate scaffold idea name:string description:string picture:string
In the command above, we specify the three properties we want to include in our idea model.
This will generate an output that looks like the code below, showing the actions that command has carried out and the files it has created.
1 invoke mongoid 2 create app/models/idea.rb 3 invoke test_unit 4 create test/models/idea_test.rb 5 create test/fixtures/ideas.yml 6 invoke resource_route 7 route resources :ideas 8 invoke scaffold_controller 9 create app/controllers/ideas_controller.rb 10 invoke erb 11 create app/views/ideas 12 create app/views/ideas/index.html.erb 13 create app/views/ideas/edit.html.erb 14 create app/views/ideas/show.html.erb 15 create app/views/ideas/new.html.erb 16 create app/views/ideas/_form.html.erb 17 create app/views/ideas/_idea.html.erb 18 invoke resource_route 19 invoke test_unit 20 create test/controllers/ideas_controller_test.rb 21 create test/system/ideas_test.rb 22 invoke helper 23 create app/helpers/ideas_helper.rb 24 invoke test_unit 25 invoke jbuilder 26 create app/views/ideas/index.json.jbuilder 27 create app/views/ideas/show.json.jbuilder 28 create app/views/ideas/_idea.json.jbuilder
As we learned at the start, out of the box, a Rails application will default to the root page. Now we have an idea endpoint, we want that to be the default page that opens when the app is started.
- Open routes.rb inside the config folder.
- Replace the contents with the following:
1 Rails.application.routes.draw do 2 root to: 'ideas#index' 3 resources :ideas 4 end
If we ran our application now, you would see one of two things: either a mostly blank page, or any ideas you added in the database outside this application — for example, using the Atlas UI or MongoDB Compass.
But we want the ability to add new ideas. We also can take this opportunity to make the application look a little better.
- Open application.html.erb.
- Replace the current file with the following code:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Inspiration</title> 5 <meta name="viewport" content="width=device-width,initial-scale=1"> 6 <%= csrf_meta_tags %> 7 <%= csp_meta_tag %> 8 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> 9 <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> 10 </head> 11 <nav class="navbar navbar-expand-lg navbar"> 12 <div class="container"> 13 <a class="navbar-brand" href="/ideas">The Idea App</a> 14 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"> 15 <span class="navbar-toggler-icon"></span> 16 </button> 17 <div class="collapse navbar-collapse" id="navbarSupportedContent"> 18 <ul class="navbar-nav mr-auto"> 19 <li class="nav-item"> 20 <%= link_to 'New Idea', new_idea_path, class: "nav-link text-info" %> 21 </li> 22 </ul> 23 </div> 24 </div> 25 </nav> 26 <body> 27 <div class="container"> 28 <%= yield %> 29 </div> 30 </body> 31 <footer> 32 <div class="container"> 33 MongoDB Atlas and Ruby on Rails <%= Time.now.year %> 34 </div> 35 </footer> 36 <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> 37 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> 38 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> 39 </html>
- Open application.css.
- Replace the current file with the following:
1 footer { margin-top: 100px; } 2 table, td, th { vertical-align: middle; border: none; } 3 th { border-bottom: 1px solid #DDD; } 4 body { margin: 0; } 5 .navbar { 6 min-height: 38px; 7 background-color: #ECA72C; 8 } 9 .navbar-brand { 10 font-size: 24px; 11 color: #080357; 12 } 13 .navbar a.brand:hover { 14 color: #fff; 15 background-color: transparent; 16 text-decoration: none; 17 } 18 .container { 19 margin: auto ; 20 }
- Make sure both files you changed are saved and run it. You should see a page similar to below where we now have a navigation bar at the top with a link to add a new idea.
I know it doesn’t look very pretty (if you have good design/CSS skills, I’m sure you could do wonderful things with this), but if you click New Idea now, it will load a form that gives you the ability to create a new idea.
You will notice that we never created this form. This is one of the powers of Ruby on Rails. Because we scaffolded out our idea model, it generated what we need to interact with it too.
Clicking the Create Idea button will then cause you to return to the idea details screen with a “success” message and your newly created idea.
You can then click to edit the idea further by using the hyperlink, or by clicking back to Ideas to view your new idea in your list of ideas. There is also a button here to delete the idea. We didn’t have to configure any of it — phew!
The best part is, thanks to us configuring the MongoDB driver, this idea will be stored in Atlas and you can see the idea inside your database, using any of the tools available. Below is an image of this being viewed inside Compass.
Just like that, with a few CLI commands and some code changes, we have a working Ruby on Rails application that allows us to create, read, update, and delete ideas, all stored inside MongoDB Atlas for free!
Of course, as mentioned earlier in the article, this doesn’t look great, so you may want to play with the styling to make it look better. But that is outside the scope of this article.
But one feature we are going to add in a future post you can look out for is the ability to search for an idea using Atlas Search, MongoDB’s full-text search feature that runs on Apache Lucene.
Thanks again to Rails Girls London for inspiring this post and for the excellent guide that gave such a great foundation to build on!