“What is CRUD?”
My phase-2 project at Flatiron School was to create a CRUD app using Sinatra. CRUD stands for “Create, Read, Update, Delete”, and in this blog I will run through the steps I used to reach the CRUD goal. In my app, you the user can create teams of 5 Champions. For this, we will need a teams table.
In this “teams” table, we are storing a some information for teams in a database. (team_name, the user the team ‘belongs to’, and the teams win/loss record). Now that we have our database set up, we can begin the CRUD operation.
Here is where we create an HTTP “get” request to /teams/new. This simply checks if the user is logged in, and if so, then renders the new team form which we can create teams to our hearts content:
Now we are getting the users input and making a ‘post’ request so that we can instantiate new team objects!!
Here we are first making sure the form was filled out correctly, (includes a team name, champions, and exactly 5 champions). If so, a new team will be created and saved, then we are redirected to /teams/(team name) where we can move on to the “Read” stage of our CRUD:
Similar to our create “get” request, first in order to ‘read’ we must check to make sure the user is logged in, find all the teams that ‘belong to’ the user, then render an index where we can finally read our teams list!
In the previous ‘get’ request, all instances of teams was stored in the @teams instance variable, so in the index view, all we are doing here is iterating over the @teams array and listing each team name with a link that takes the user to a more detailed view for each team.
Similar to our other two implementations, in order to fulfill the “Update” requirements for CRUD we first make a ‘patch’ request and render a form in which the user can fill out to edit their teams. In our ‘patch’ request we and making some checks to first find the team the user wishes to edit, making sure that team exists, making sure the team belongs to the user and is ‘authorized’ to edit it, then updates the team based on the user inputs. Our form is similiar to the form we used to create a new team, minus a couple key takeaways. In this form, it is very important to note that we are overriding our ‘post’ request with a ‘patch’ request. This is done by adding ‘Rack::MethodOverride’ to the config.ru file. MethodOverride is Sinatra middleware which allows this to happen.
Finally, the D in CRUD: Delete/destroy. Again, we render a form who’s action takes us to the ‘controller’ that deletes our team(@team.destroy). Before we do that, of course we need to use the ‘redirect_if_not_team_owner’ we created. It would be super un-cool if other users could delete our teams!