Jes Jes - 1 year ago 71
Ruby Question

Sinatra - delete action

I have basic Store app - I want to be able to add product to basket and then delete it using Sinatra. My adding works, but I can't make delete to work too. I had special function for that, but now I just want to see whether delete route works at all. My main app has many routes, and part I'm talking about is:

post '/basket' do #it works, adds to basket and redirects
redirect '/'

delete "/basket/delete" do #it doesn't work at all and doesn't redirect
basket = BASKET.find{|p| == params["id"]}
redirect "/"

In HTML I have:

<% basket.each do |b| %>
<form action="basket/delete" method="post">
<input type="hidden" name="_method" value="delete">
<input type="hidden" name="id" value=<%= %>>
<button type="submit">Delete</button>
<% end %>

As you can see, after clicking on "Delete" button, I'm sending "id" in my params helper.

basket = BASKET.find{|p| == params["id"]}

should find one specific item with this id and delete it from my big array BASKET. But it doesn't work, after clicking on "Delete" I'm otransferred to basket/delete page and I have an error, because post for basket/delete doesn't exist. It should redirect me to my index page. What's more, it doesn't delete my basket item, it still exists. I'll appreciate any help.

Answer Source

You need this component in your middleware pipeline use Rack::MethodOverride

Another way seems to be put set :method_override, true in your Sinatra::Base class

See this also