Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 983
Michael Liu Avatar asked Jul 10 '13 15:07

Michael Liu


1 Answers

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.

like image 152
Marek Lipka Avatar answered Sep 20 '22 14:09

Marek Lipka