Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
MongoDBchevron-right

Building Rails Applications With the MongoDB Template

Joel Lord4 min read ā€¢ Published Aug 26, 2024 ā€¢ Updated Aug 26, 2024
MongoDBRuby
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty

Building Rails Applications With the MongoDB Template

After over 20 years, Ruby on Rails is still a popular framework for web development. Its MVC (Model-View-Controller) architecture provides an easy way to build a clean, well-structured, and scalable web application.
Out of the box, Rails integrates with a traditional relational database, but this can easily be changed to use MongoDB. The instructions are in our getting started guide. However, if you simply want to create a fully functional application, you can use the MongoDB Rails template, as explained in this tutorial.

Requirements

For this tutorial, you will need:

About the MongoDB-Rails template

This template uses Mongoid, the MongoDB maintained driver, to connect and interface with the database. For styling, we kept things simple and utilized tailwindcss-rails. Everything else should be the same as a vanilla Rails project.

Getting started

Start by creating a new Rails project. You must use the --skip-active-record flag so it doesnā€™t install those gems. These will be replaced with the mongoid gem.
1rails new rails-mongodb -m https://raw.githubusercontent.com/mongodb-developer/rails-mongodb/main/template.rb --skip-active-record
When prompted, enter the connection string to your MongoDB cluster. The Atlas UI provides the connection string.
You now have everything you need to start your web server.
1cd rails-mongodb
2rails s
Now, you should be able to point your browser to http://localhost:3000 and see the application running. Easy peasy! Youā€™ve got a Rails application that connects to your MongoDB database. From this UI, you can see the list of movies from the sample_mflix database. Clicking on a title will bring you to the details page to see the movie's plot. You can also click on the trash icon next to the movies to delete them.
You also have a search bar at the bottom, which lets you search for movies by title. You even have a form to add new movies.

Exploring the application

You have a basic application, but now what? Chances are you have a different dataset, and you want to connect to it. Here, we describe the various components of this application and how you can edit them for your data.

Database connection

Mongoid manages the database connection. The connection string is in the config/mongoid.yml file. You can change it here to connect to a different cluster. The driver will take care of managing the database connections, so you shouldnā€™t need to do more here.

Movies MVC

To create our movie model, we used the standard Rails scaffolding. For the purpose of this application, our movies only have three fields: title, plot, and year.
1bin/rails g scaffold Movie title:string plot:text year:integer
You will recognize the default files listed in the app/models, app/controllers, and app/views folders for the application's MVC components.

Models

The model for the movies can be found in the app/models/movie.rb file.
1class Movie
2 include Mongoid::Document
3 store_in database: 'sample_mflix'
4
5 include Mongoid::Timestamps
6 field :title, type: String
7 field :plot, type: String
8 field :year, type: Integer
9end
As you can see, our three fields and the timestamps are listed here. This will automatically handle the updated_at and created_at fields in your document.
In this case, we added the store_in database: 'sample-mflix' line. Normally, this would be handled in your connection string stored in the config/mongoid.yml file. It is here solely for the educational purpose of the article.

Controllers

Next, the code for our movie controller can be found in the app/controllers/movies_controller.rb file. Mongoid generated most of the code in this controller, which also contains the code to retrieve some of the movies from the database.
1 # GET /movies or /movies.json
2 def index
3 @movies = Movie.limit(10)
4
5 # Return movies if a form was posted with a search term
6 if params[:search]
7 @searched_movies = Movie.where(title: /#{params[:search]}/i)
8 end
9 end
We do two things here.
First, we fetch 10 movies from the database with Movie.limit(10). We donā€™t have any specific query filters for this one, but we didnā€™t want to load all the movies from our database in our view.
Secondly, we look for a query parameter called search. If itā€™s present, we do a slightly more complex query to retrieve movies that match this filter. In this case, we use the filter (title: /#{params[:search]}/i). This will use a regular expression to find movie titles that match the query.
Using a regex to query text is not optimal as it canā€™t use the indexes. While this works for this demo application, you should look into using Atlas Search for your production application.
Nothing else was changed in this file, so you can see how the generated code can provide you with all the basic functionalities. We left the update function in the file, even if the application doesnā€™t use it, so you can see what the update code would look like.

Views

Finally, you have your views. You can find them in the app/views/movies folder. There is a view for each of our application's pages and a partial view to list movies.
The HTML on the views was changed slightly from the default Rails code to make it more aesthetically pleasing when looking at the application, but most of the code stayed the same. We used the original code in app/views/movies/index.html.erb to display the movies on the main page.
1 <% @movies.each do |movie| %>
2 <%= render movie %>
3 <% end %>
This will generate each movie in the list using the partial template app/views/movies/_movie.html.erb.
The partial template was also kept at the bare minimum.
1<div id="<%= dom_id movie %>">
2 <%= link_to "šŸ—‘ļø", movie_path(movie), data: { turbo_method: :delete } %>
3 <%= link_to " #{movie.title} (#{movie.year})", movie_path(movie) %>
4</div>
You can see here that we list the movie title and year, and link to the movie details page. The trash icon uses the { turbo_method: :delete } link to delete the movie from the collection immediately.
As you would expect from a Rails application, we rely mostly on the coding conventions to share the data from the controllers to the views so that the movies can be displayed.

Next steps

Thatā€™s it! You have the basics to connect to your database and run the CRUD (create, read, update, delete) operations on your collections. This is all you need to build your application on Rails. If you want to learn more, you can use the link provided in the navigation bar from the application.
Now, try adding more pages to your application. Adding a collection for the actors would be a great place to start. And if youā€™re feeling adventurous, you can add a section to add comments associated with movies. You can find an example of this in the getting started guide. If you need help, contact us on the community forums, and weā€™ll be happy to help.
Top Comments in Forums
There are no comments on this article yet.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Massive Number of Collections


Oct 01, 2024 | 6 min read
Quickstart

Java - Aggregation Pipeline


Oct 01, 2024 | 8 min read
Article

Using AWS Rekognition to Analyse and Tag Uploaded Images


Sep 11, 2024 | 1 min read
Quickstart

MongoDB Cheat Sheet


Sep 29, 2023 | 5 min read
Table of Contents
  • Building Rails Applications With the MongoDB Template