Issue in rails 4.0 with creating a link_to for a delete action

梦想的初衷 提交于 2019-12-08 16:47:24

问题


This is my first project in rails, which is to create a table that will store data about games. I'm able to display data from the table about winner score, loser score, etc. However, I have issues with my table column that contains delete links for each game.

Here's my code in the games controller for the delete method:

def delete
  @game = Game.find(params[:game])
  @game.destroy()
  redirect_to :action => 'index'
end

A snippet of my table code, which includes the line for the link_to command

    <% @games_items.each do |t| %>
     <tr>
        <td><%= t.winner.name %></td>
        <td><%= t.loser.name %></td>
        <td><%= t.challenger.name %></td>
        <td><%= t.winner_score %></td>
        <td><%= t.loser_score %></td>
        <td><%= link_to 'Delete', delete_game_path(id: t.id)%></td>
     </tr>
    <% end %>

In the routes file I called

resources :games

Which, to my knowledge, helps generate the base routing. Could anyone help me figure out why my link_to is not working?


回答1:


If you use (which is adviced) resources: a) Your action for deleting records should be named destroy. b) Game is searched for with :id parameter:

def destroy
  @game = Game.find(params[:id])
  @game.destroy
  redirect_to :action => 'index'
end

c) Your link should be:

<%= link_to 'Delete', t, method: :delete %>

since the path is the same as for the show action, the only thig that changes is HTTP method.




回答2:


The format for the delete call is:

<%= link_to 'Delete', game_path(t.id), :method => :delete %>

use rake routes to learn about the available routes, including generated route helpers, and the controller/action handling the request.




回答3:


I had similar issue on rails 4.2.1, even with the :method => :delete on link_to it still routes to show method.

But using button_to method as below works!

<%= button_to "delete", article_path(:id => article.id), :method => :delete %>

button_to creates a form around the button and then posts to the delete method, by adding a hidden field named _method with value delete rails uses this to route to the destroy method in your controller.




回答4:


Try to use <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> before <%= javascript_include_tag "application" %> in your layout, and also delete

//= require jquery

line in your application.js. This was the case for me. No idea why it didn't worked with original rails jquery.js file.



来源:https://stackoverflow.com/questions/17574370/issue-in-rails-4-0-with-creating-a-link-to-for-a-delete-action

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