Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernardobarreto/d90f63cac9c6b6c2afa6bd18f5fee4c8 to your computer and use it in GitHub Desktop.
Save bernardobarreto/d90f63cac9c6b6c2afa6bd18f5fee4c8 to your computer and use it in GitHub Desktop.
How Sinatra routes PUT/PATCH and DELETE

HTML and Sinatra really only support the GET and the POST methods. In order to be able to use the PUT and DELETE methods in Sinatra, you kind of have to "trick" the form to go to the right place. Then you can name the routes the proper way - otherwise you can only really work with GET and POST.

I used the Craiglist Jr challenge for some examples. Let's look at a quick example of a POST form/method/route- in this case, we're creating a new Craigslist article:

POST form and corresponding route:

<form action="/article/new" method="post">
  --------------------------------
  YOUR FORM FIELDS HERE
  --------------------------------
  <input type="submit" value="Create Article">
</form>

post '/article/new' do
  @category_object=Category.find_by(params[:category_selection])
  @category_object.articles.create(params[:article])
  redirect to("/category/#{@category_object.name}")
end

Now let's see how PUT and DELETE forms differ from the POST method.

PUT form and corresponding route:

<form action="/article/<%=@article_object.id%>" method="post">
  <input type="hidden" name="_method" value="PUT">
  --------------------------------
  YOUR FORM FIELDS HERE
  --------------------------------
  <input type="submit" value="Edit Article">
</form>

put '/article/:id' do
  @article_object = Article.find(params[:id])
  @article_object.update(params[:article])
  redirect to("/article/#{params[:id]}")
end

DELETE form and corresponding routing:

<form action="/article/<%=@article_object.id%>" method="post">
  <input type="hidden" name="_method" value="DELETE">
  <input type="submit" value="Delete Article?">
</form>

delete '/article/:id' do
  @article_object = Article.delete(params[:id])
  redirect to("/")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment