Reputation: 1131
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?
Upvotes: 8
Views: 17886
Reputation: 7391
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.
Upvotes: 0
Reputation: 3403
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.
Upvotes: 5
Reputation: 51151
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.
Upvotes: 17
Reputation: 3266
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.
Upvotes: 6