Search code examples
ruby-on-railsrubyroutesdestroy

No route matches [POST] - Rails destroy


I am new to RoR and still don't have enough experience on solving the different errors that may appear to me. In this case I am designing a blog where I can post articles. More specifically, my problem is related to deleting these articles.

As far as I know, writing:

resources :articles

in the routes file is an alternative for writing:

get "/articles"            #index
post "/articles"           #create
delete "/articles/:id"     #delete
get "/articles/:id"        #show
get "/articles/new"        #new
get "/articles/:id/edit"   #edit
patch "/articles/:id"      #update
put "/articles/:id"        #update

When I try to delete an article I get the following error:

No route matches [POST] "/articles/1"

The code I wrote was:

View

<% @articles.each do |art| %>
    <%= art.title %>
    <div>
        <%= art.body %> - <%= link_to "Delete", art, method: :delete %>
    </div>
<% end %>

Controller

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path       
end

Solution

  • It sounds like you have this in your view:

    <%= art.body %> - <%= link_to "Delete", art, method: :destroy %>
    

    But you actually need:

    <%= art.body %> - <%= link_to "Delete", art, method: :delete %>
    

    I'd advise double-checking this in your app based on your reply to a comment from @GonzaloRobaina.