Ruby Controllers using Sinatra
My most recent project has been the first of many to come where I felt able to fully understand the logic of both backend and frontend while building. I decided to build a simple React app that allows a user to add & delete movies in their collection, rate movies, and display back the average of all ratings for that movie.
This required a few routes in my ApplicationController to handle the HTTP requests. In this post, I’m going to cover the routes I used in this build. To see more, my project code can be accessed here.
Right to it:
Our initial GET route is very simple. get “/movies” do Movie.all.to_json end
This pretty much tells the server to respond to a get request from the client that has a route ending in /movies with all of our Movie objects in json format.
The same principles apply to our ratings path, get “/ratings” do Rating.all.to_json end
Our final GET request allows us to pull data for individual movies upon request, get “/movies/:id” do movie = Movie.find(params[:id]) movie.to_json end
This communicates to our server to respond with the Movie object in json format that has an id parameter matching the requested path.
The same principles apply to our DELETE request for /movies/:id. One difference is we use movie.destroy to eliminate the contents of the object, then return the now empty object in json format. Note here that we could also decide to return a message along the lines of “Movie has been deleted” or something to that effect.
Finally, we’ll cover our POST requests.
post ‘/movies’ do movie = Movie.create( name: params[:name], director: params[:director], cover: params[:cover] ) movie.to_json end
Here, we set a variable, movie, to a created object with parameters that match the parameters we set for our Movie class. Those parameters would be name, director, and cover. We then return to the client the movie variable as a json object.
And like before, the same principles apply to our ratings POST request. Only with different parameters. For the Rating class, our parameters are rating and the foreign key of movie_id.