Question

What is usually a simple error with a simple solution, I seem to be stuck:

posts#controller:

class PostsController < ApplicationController

def index
 @posts = Post.all
end

def show
 @post = Post.find params[:id]
end

def new
 @post = Post.new
end

def create
 @post = Post.create post_params

 if @post.save
  redirect_to posts_path, :notice => "Your post was saved!"
 else
  render 'new'
 end

end

private
 def post_params
  params.require(:post).permit(:title, :content)
 end

def edit
 @post = Post.find params[:id]
end

def update
 @post = Post.find params[:id]

 if @post.update_attributes params[:post]
  redirect_to posts_path
 else
  render 'edit'
 end
end

def destroy
 @post = Post.find params[:id]
 @post.destroy

 redirect_to posts_path, :notice => "Your post has been deleted"
end

end

routes.rb:

Blog::Application.routes.draw do

 resources :posts

end

rake routes:

Prefix Verb   URI Pattern               Controller#Action
posts GET    /posts(.:format)          posts#index
      POST   /posts(.:format)          posts#create
new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
post GET    /posts/:id(.:format)      posts#show
      PATCH  /posts/:id(.:format)      posts#update
      PUT    /posts/:id(.:format)      posts#update
      DELETE /posts/:id(.:format)      posts#destroy

posts view, index.html.slim:

h1 Blog
- @posts.each do |post|
 h2 = link_to post.title, post
 p = post.content
 p = link_to 'Edit', edit_post_path(post)
 p = link_to 'Delete', post, :confirm => "Are you sure?", method: :delete
 br

p = link_to 'Add a new post', new_post_path

Yet I continue to get an error inside the browser showing:

Unknown action, The action 'destroy' could not be found for PostsController

I seem to be getting a few of these basic problems since I updated to Rails 4, probably a minor oversight, anyone got any ideas?

Was it helpful?

Solution

PostsController#destroy is under your private declaration, so it's a private method -- there are restrictions on how it can be called.

Try moving def destroy ... end above the word private (and protecting that route another way, if appropriate). If for some reason you still need to call a private method, you can use #send, for example:

PostsController.new.send :destroy # and any arguments, comma-separated

(Using #send this way makes no sense for a Rails controller, but it might come in handy another time!)

OTHER TIPS

In posts_controller.rb, try using this code

def destroy
  Post.find(params[:id]).destroy
  redirect_to posts_path
end

And in index.html.erb use

<%= link_to "Delete", post, :data => {:confirm => "Are you sure?"}, :method => :delete %>

Figured it out using rails 4.2.5.1. I think this is rails 4.x specific but it might work on other versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top