0

一个简单的解决方案通常是一个简单的错误,我似乎被卡住了:

帖子#控制器:

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

路线.rb:

Blog::Application.routes.draw do

 resources :posts

end

耙路线:

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 的操作“销毁”

自从我更新到 Rails 4 后,我似乎遇到了一些这些基本问题,可能是一个小小的疏忽,有人有什么想法吗?

4

2 回答 2

2

PostsController#destroy在你的private声明下,所以它是一个私有方法——它的调用方式有限制。

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

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

(使用#send这种方式对 Rails 控制器来说毫无意义,但下次它可能会派上用场!)

于 2013-10-15T04:53:11.447 回答
0

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

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

并在 index.html.erb 中使用

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

使用 rails 4.2.5.1 弄清楚了。我认为这是特定于 rails 4.x 的,但它可能适用于其他版本。

于 2017-04-02T09:17:37.807 回答