'Ruby on Rails: Delete link to redirects to show page
I'm working on a rails 5.0 application. It's a legacy application and has been poorly maintained over the years and god knows what hasn't been updated on it properly (for example, its still using a public/ structure to contain all of its stylesheet and javascript files).
I'm having trouble getting the default rails delete routes to execute.
Consider the following controller action:
class Admin::PackagesController < ApplicationController
def destroy
@package = Package.find(params[:id])
@package.destroy
respond_to do |format|
format.html { redirect_to root_url}
format.xml { head :ok }
end
end
But when I call the following link:
<%= link_to 'Destroy', ['admin', package], :confirm => 'Are you sure?', :method => :delete %>
It doesn't call the destroy action: it goes to the show action for the individual package.
Solution 1:[1]
I'm not sure if this is still an issue but I ran into it with a Rails 7 blog/comments app. The following code within a 'comment' partial (for Post show page) and a comment controller fix solved the issue for me.
_comment.html.erb:
<%= link_to 'Delete', [comment.post, comment], data: { turbo_method: :delete, turbo_confirm: 'are you sure?' }, class: 'button is-danger' %>
comments_controller.rb:
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post), status: :see_other
end
The status: :see_other section of the redirect was essential in it working and understanding how Rails handles redirects and this link helped a lot!
Solution 2:[2]
<%= link_to 'Destroy', package_path(package), method: :delete %>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dan |
| Solution 2 | John Skiles Skinner |
