Why Rails “link_to” does not work for delete action?

ⅰ亾dé卋堺 提交于 2019-11-27 18:06:03

问题


In index.html.erb I display all products, and next to each product I have Edit and Delete actions:

<% @products.each do |product| %>
  ...
  <%= link_to("Edit", edit_product_path(product.id), :class => 'action') %>
  <%= link_to("Delete", product, :method => :delete, :class => 'action') %>
  ...
<% end %>

The Edit link works ok. However, the Delete link does not work. I get the following error:

Unknown action
The action 'show' could not be found for ProductsController

I guess it is because the request method is GET rather than DELETE. But, I don't know why this happens if I set explicitly :method => :delete.

routes.rb is pretty simple:

root :to => "products#index"
resources :products

I have Javascript enabled.

Please suggest.


回答1:


Do you have rails.js specified in a javascript_include_tag? This is required for the unobtrusive DELETE method to work. If you're using jQuery then there's a solution for that too.




回答2:


Dont forget to include jquery_ujs in your application.js file:

//
//= require jquery
//= require jquery_ujs
// ...



回答3:


It needs to be product_path(product) instead of product in your delete link.




回答4:


I had same problem - actually I had changed my old 'delete' action to 'destroy' - but forgot If your using SSL.. (e.g ssl_required :destroy)



来源:https://stackoverflow.com/questions/4446697/why-rails-link-to-does-not-work-for-delete-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!