Rails 4,未知动作,无法找到PostsController的动作'destroy'

时间:2013-10-15 04:19:43

标签: ruby-on-rails ruby ruby-on-rails-4 slim-lang

通过一个简单的解决方案通常是一个简单的错误,我似乎陷入困境:

帖子#控制器:

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

发布视图,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

但是我在浏览器中继续显示错误:

未知操作,无法找到PostsController

的操作'destroy'

自从我更新到Rails 4后,我似乎得到了一些基本问题,可能是一个小小的疏忽,任何人都有任何想法?

2 个答案:

答案 0 :(得分:2)

PostsController#destroy在您的private声明之下,因此它是private method - 对如何调用它有一些限制。

尝试将def destroy ... end移到单词private上方(如果合适,以另一种方式保护该路线)。如果由于某种原因您仍需要调用私有方法,则可以使用#send,例如:

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

(使用#send这种方式对于Rails控制器没有任何意义,但它可能会在另一个时间派上用场!)

答案 1 :(得分:0)

在posts_controller.rb中,尝试使用此代码

&#13;
&#13;
def destroy
  Post.find(params[:id]).destroy
  redirect_to posts_path
end
&#13;
&#13;
&#13;

在index.html.erb中使用

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

使用rails 4.2.5.1进行计算。我认为这是rails 4.x特定的,但它可能适用于其他版本。