Sending a DELETE request from Sinatra

2020-05-23 01:17发布

I am trying to develop a RESTful Sinatra application. Now, I know how to respond to a delete request with something like

delete '/user/:id' do |id|
   #do something in the model
end

What I am interested in is how do I get to execute that method. I can't have link that does a DELETE instead of a GET, can I?

The only solution I found so far is sending a DELETE request via jQuery: How to send a PUT/DELETE request in jQuery?

I tried looking into different RESTful Sinatra projects on github but my Ruby knowledge is probably to limited to get how they are doing it.

5条回答
Anthone
2楼-- · 2020-05-23 01:36

see also Call Sinatra delete route with jQuery for how to do this with jQuery and JSON at the front end and Sinatra on the back end.

查看更多
混吃等死
3楼-- · 2020-05-23 01:41

I thinks it's like the Rails way. You need define a params '_method' with 'delete' value and add it on your form.

When you POST you form with this particular params, you do a DELETE request in sinatra.

Like :

<form action="/search" method="post">
  <div style="margin:0;padding:0">
    <input name="_method" type="hidden" value="delete" />
  </div>
</form>

It's the same with PUT method

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-05-23 01:43

Put following line in your code.

use Rack::MethodOverride

It will help you interpret post methods with parameter "_method" with value "delete" as put. Then you can write

delete '/user/:id' do |id|
查看更多
ゆ 、 Hurt°
5楼-- · 2020-05-23 01:49
  %form{:action => "/note/delete/#{@note.id}", :method => "post"}
    %input{:type => 'submit', :name=> "_method", :value => 'delete', :class => 'button'}

You can also trigger the delete route with a button like so

查看更多
Lonely孤独者°
6楼-- · 2020-05-23 01:56

Another way is to use Curl:

curl -X DELETE http://host/user/1
查看更多
登录 后发表回答