Ester Lin
Ester Lin

Reputation: 617

Rails The action 'destroy' could not be found error

I've seen similar questions posted about this issue but the solutions offered there don't seem to be the problem for me.

I have a page where users can choose to edit or delete location files and it's coded with this each block:

<%current_user.locations.reverse.each do |l|%>
<%=l.address %> 
<a href=<%= edit_location_path(l) %> class="btn btn-primary">Edit</a>
| <%= link_to "delete" class="bg-danger", l, method: :delete,
                              data: { confirm: "You sure?" } %>
<br>
<%end%>

I have in my routes (had both to try and fix this error):

 get 'locations/:id/delete' => 'locations#destroy'
 get 'locations/:id/destory' => 'locations#destory'
 resources :locations

And I have this coded in the locaction controller:

def destory
 @location = Location.find(params[:id])
 @deleted_address = @location.address
 @location.destroy
 flash[:danger] = @deleted_address + " deleted"
 redirect_to current_user
end

I can't figure out why rails can't find my destroy action (redirect works fine for other actions).

Upvotes: 1

Views: 1495

Answers (3)

messanjah
messanjah

Reputation: 9278

These issues jump out at me:

Firstly, fix destory typos.

# routes
'locations/:id/destroy' => 'locations#destroy'

#controller
def destroy

Secondly, use HTTP DELETE verb for destroy.

delete 'locations/:id/destroy' => 'locations#destroy'

Lastly, the link_to should specify the location path.

<%= link_to "delete", location_path(l), class: "bg-danger", method: :delete,
        data: { confirm: "You sure?" } %>

Upvotes: 0

Richard Peck
Richard Peck

Reputation: 76774

Do this:

#config/routes.rb
resources :locations #-> DELETE url.com/locations/:id goes to destroy action

#view
<%current_user.locations.reverse.each do |l|%>
   <%=l.address %> 
   <%= link_to "Edit", l, class: "btn btn-primary" %>
   <%= link_to "Delete", l, method: :delete, class: "bg-danger", data: { confirm: "You sure?" } %> 
<% end %>

This will send a request to your locations#destroy action.

The issue you have currently is that you're calling link_to with some strange ordering:

<%= link_to "delete" class="bg-danger", l, method: :delete, data: { confirm: "You sure?" } %>

... should be ...

 <%= link_to "Delete", l, method: :delete, class: "bg-danger", data: { confirm: "You sure?" } %>

As per the docs:

link_to(name = nil(link text), options = nil (controller/url), html_options = nil(class/id/data), &block) 

Upvotes: 1

Graham S.
Graham S.

Reputation: 1530

You are calling method: :delete in your link, which is correct.

The only other problem I see is that you spelled destroy wrong. You spelled it destory like "dee-stor-ee".

I would remove this route as well:

 get 'locations/:id/destory' => 'locations#destory' #=> wouldn't work anyways because it's not a "delete" request

since you are already calling resources :locations.

Upvotes: 1

Related Questions