8

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?

4

4 回答 4

17

如果您使用(建议)resources: a) 您删除记录的操作应命名为destroy:idb) 使用参数搜索游戏:

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

c)您的链接应该是:

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

由于路径与show动作相同,唯一改变的是 HTTP 方法。

于 2013-07-10T15:16:10.613 回答
6

删除调用的格式是:

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

用于rake routes了解可用的路由,包括生成的路由助手,以及处理请求的控制器/动作。

于 2013-07-10T15:16:27.187 回答
5

我在 rails 4.2.1 上遇到了类似的问题,即使在 link_to 上使用 :method => :delete 它仍然路由显示方法。

但是使用下面的 button_to 方法有效!

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

button_to 在按钮周围创建一个表单,然后发布到 delete 方法,通过添加一个名为_methodvalue的隐藏字段deleterails 使用它来路由到控制器中的 destroy 方法。

于 2015-04-21T15:00:25.217 回答
0

尝试在您的布局中使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>before<%= javascript_include_tag "application" %>并删除

//= require jquery

行在你的 application.js 中。我就是这种情况。不知道为什么它不适用于原始 rails jquery.js 文件。

于 2016-01-16T08:14:09.950 回答