'Why is my RoR link pointing to the wrong controller action?

I have the following in my projects_controller.rb:

def destroy
    @project = Project.find_by_slug(params[:id])
    @project.destroy
    redirect_to projects_url
end

And I have the following in my routes.rb file:

delete "projects/:id", to: "projects#destroy", as: "destroy_project"

I have the following link (inside the show.html.erb file):

<%= link_to destroy_project_path(@project), method: :delete, class: "btn-gradient btn-red" do %>
    <span>Delete Project</span>
<% end %>

Upon clicking the button, the page reloads. The show action is called upon clicking the button. I've added console logs in each method, and it is clear that the destroy action is never called.

Can anyone point me in the right direction?



Solution 1:[1]

the link_to helper receives 2 different sets of hashes for the options.

The first set is for things like the http method, and the second for the html attributes (class, id and so on)

The way you wrote it, you probably have method=delete in your query params, which is wrong. You have to explicitly enclose the method: :delete within its own options hash:

<%= link_to destroy_project_path(@project), { method: :delete }, class: "btn-gradient btn-red" do %>
    <span>Delete Project</span>
<% end %>

Solution 2:[2]

If you use rails 7 with turbo framework you can try below for buttons.

<%= button_to "Delete this project", destroy_project_path(@project), method: :delete %>

Or you can try below for links.

 <%= link_to destroy_project_path(@project.id) ,  data: { turbo_method: :delete }  do %>      
    <span>Delete Project</span>
 <% end %>

Solution 3:[3]

the problem that you are having is with the JS. there is a problem where something is not loading properly.

For testing try to remove your JS and use something like this

<%= javascript_include_tag "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" %>

When you get the delete method working, then you can debug where in your JS there is a problem.

at this time there is not sufficient info on your question to be able to know what it is.

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 Fer
Solution 2 Sercan T?rnaval?
Solution 3 MZaragoza