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?
CodePudding user response:
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 %>
CodePudding user response:
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 %>