简体   繁体   中英

Delete method rails 6

I made a web application that allows the user to add edit and delete an article. The problem I'm having is that the delete method does not work. When I click "Delete" beside the article that i want to get rid off nothing happens, I don't get any errors either. I think its acting as a GET method rather than a DELETE method but I have no idea why it won't work.

Any help will be greatly appreciated!

articles_controller.rb

def destroy
  @article = Article.find(params[:id])
  @article.destroy
  redirect_to articles_path
end

index.html.erb

<tbody>
  <% @articles.each do |article| %>
  <tr>
    <td><%= article.title %></td>
        <td><%= article.description %></td>

        <td><%= link_to 'Show', article_path(article) %></td>
        <td><%= link_to 'Edit', edit_article_path(article) %></td>
        <td><%= link_to 'Delete', articles_path(article), method: :delete, data: {confirm: "Are you sure?"} %></td>

  </tr>
  <% end %>

Console when i click Delete:

Started GET "/articles.5" for ::1 at 2020-03-26 16:45:32 +0000
Processing by ArticlesController#index as
  Rendering articles/index.html.erb within layouts/application
  Article Load (0.4ms)  SELECT "articles".* FROM "articles"
  ↳ app/views/articles/index.html.erb:14
  Rendered articles/index.html.erb within layouts/application (Duration: 4.1ms | Allocations: 1596)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layouts/_navigation.html.erb (Duration: 0.3ms | Allocations: 85)
Completed 200 OK in 72ms (Views: 70.3ms | ActiveRecord: 0.4ms | Allocations: 8290)

routes.rb

Rails.application.routes.draw do
  root 'pages#home'
  resources :articles, only: [:show, :index, :new, :create, :edit, :update, :destroy]

end

Application.js

require("@rails/ujs").start()
require jquery
require jquery_ujs
require bootstrap-sprockets
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

I figured out a fix for this problem. By changing

<td><%= link_to 'Delete', article_path(article), method: :delete, data: {confirm: "Are you sure?"} %></td>

to

<td><%= button_to 'Delete', article_path(article), method: :delete, data: {confirm: "Are you sure?"} %></td>

This fixed my issue.

This is wrong.

<td><%= link_to 'Delete', articles_path(article), method: :delete, data: {confirm: "Are you sure?"} %></td>

It should be...

<td><%= link_to 'Delete', article_path(article), method: :delete, data: {confirm: "Are you sure?"} %></td>

Use the article show path, not the arcticles index path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM