Reputation: 1642
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 %>
Upvotes: 0
Views: 1050
Reputation: 8121
Change the code in your delete.html.erb to
<h2>Delete</h2>
<%= @article.title %> <%= button_to 'Delete It', article, method: :delete %>
Upvotes: 1
Reputation: 33542
Firstly,your destroy
method is not valid and not necessary.Remove it from the controller.
change your delete
methods as
def delete
@article= Article.find(params[:id])
if @article.destroy
redirect_to(:action => 'index')
else
render 'delete'
end
And finally,change your form_for
as
<%= form_for :article, :url => url_for(:action => 'delete', :id => @article) do |f| %>
<%= @article.title %>
<%= submit_tag("Delete It") %>
<% end %>
Note: And also as @brendon mentioned,change your controller name to plural.As per now it is singular which is against the naming conventions of Rails.
Upvotes: 1
Reputation: 1318
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.
Upvotes: 4