DEV Community

Doug Jones
Doug Jones

Posted on

RESTful Routes & DELETE

What is a RESTful Route?

Let's start with what is Rest? Rest stands for (REpresentational State Transfer). This provides a pattern for developers to use when building routes.

A Restful Route provides mapping from our HTTP Verbs to our CRUD (Create, Read, Update, Delete) controller actions. Our CRUD actions are a combination of HTTP verbs and action.This makes it easier for developers and users to understand whats happening as they use a web application.

Alt Text

The Delete Action

One element in our C.R.U.D application is Delete.
What makes our Delete method different is that it works with Sinatra Middleware via (Rack::MethodOverride), because our browsers don't recognize this verb.

In order to use Rack::MethodOverride we must tell our app to use the middleware.

The delete method needs to be submitted as a post request. In order to make this work our form must include a "hidden" input felid to communicate with our Sinatra middleware. We also include a name=" _method" to tell our middleware to translate the forms tags attribute and value= "delete"

Here is a form for our delete method:

<form method="post" action="/games/<%= @games.id %>/delete" >
 <input type="hidden" id="hidden" name="_method" value="delete">
 <input type="submit" value="Delete Game">
</form>
Enter fullscreen mode Exit fullscreen mode

Here is our delete controller:

 delete "/games/:id/delete" do
    @games = Game.find_by_id(params[:id])
    @games.destroy
    redirect "/games"     
  end

Enter fullscreen mode Exit fullscreen mode

This action finds the games in the database based on the ID in the url parameters and deletes it. It then redirects to the index page where all of our games are displayed minus the one we just deleted.

Top comments (0)