Corny title and weak analogy aside, I've just completed my latest iteration of a movie review application. The objective of this project was to create a single-page application using Ruby on Rails API for the backend and JavaScript/HTML/CSS for the frontend. The two parts of the application communicated asynchronously using JSON. Here is a link to the frontend repository as well as the backend repository. To try out the application yourself, simply clone both repositories to your machine, run bundle, start the rails server, and open the html file from the frontend in your browser.
Backend: Rails API
To create the rails backend, I created a new rails project using the --api
flag. I used the resource generator to create the skeleton of what I needed to handle movies and reviews in rails. To protect the data on the server side, I added validations to both my Movie and Review models. For example, I created a method to put a movie's title in title case before it's persisted to the database. For reviews, I used a validation to make sure that the rating was between 1 and 5.
The biggest change from the last project to this one was that ruby was no longer handling the views for the application. Long gone are the html.erb files (dramatic I know). Instead of rendering the view for a given action (index, show, etc.), I rendered the relevant object in JSON format. To make that process easier, I used the Active Model Serializer gem to convert my rails objects into the JSON that would be fetched by the frontend of my application.
Frontend: JavaScript/HTML/CSS
Since this was a single-page application, there was only one html file. After thinking about how I was going to display everything on the page, I made the outline of the app in the index.html file. This included the form to create a new review, a section to display all of the movies with all of their reviews, and a form to create a new movie at the bottom of the page. Of course if this app were to be in production, you'd want more control over who's allowed to add/delete movies.
After creating the skeleton of my webpage, I moved on to building my JavaScript files (one per class). I made the MovieApi class to create an instance that would handle the API calls to the rails backend. This is where the methods to READ all the movies in the database, CREATE new movies, and DELETE movies reside. The Movie class is responsible for creating movie objects and displaying them on the webpage. I had two similar classes for my ReviewApi and Reviews, respectively. Using elements that I created in the html file, I added elements that represented the movie and review data to the DOM.
Top comments (0)