Search code examples
ruby-on-railsrubyruby-on-rails-4destroy

Unknown action, Ruby on Rails 4 Beginner, destroy action is unknown


I get " The action could not be found for ArticleController " After pressing "delete It", on my delete page. I think it can not find destroy function! What is missing here?

Controller:

class ArticleController < ApplicationController

def index
  @article= Article.all
end

def show
  @article= Article.find(params[:id])
end

def new
 @article= Article.new
end

def create
  @article= Article.new(user)

  if @article.save
      redirect_to(:action => 'index')
  else
      redirect_to(:action => 'index')
  end
end

def delete
  @article= Article.find(params[:id])
end

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

private
  def user
  params.require(:article).permit(:title, :text)
  end
end

The routes.rb

 Rails.application.routes.draw do

  resources :article 
   match ':controller(/:action(/:id))', :via => [:get, :post]
  #..

my delete.html.erb

  <h2>Delete</h2>

  <%= form_for :article, :url => url_for(:action => 'destroy', :id => @article) do |f| %>
    <%= @article.title %>
    <%= submit_tag("Delete It") %>
  <% end %>

Solution

  • I see a few things wrong with the code you posted.

    First, your controllers should be the plural name of your resource so in this case it should be ArticlesController.

    Second, in regards to the error you're getting, when using resources :articles in your routes file the destroy action is mapped to a DELETE request. Your form is trying to GET the destroy action.

    What you'll want to do to fix that is

    <%= form_for :article, :url => url_for(:action => 'destroy', :id => @article), :method => :delete do |f| %>
    

    Take a look at the Rails Routing Guide for more information on how Rails uses REST.