2013-10-15 46 views
0

什麼通常是一個簡單的解決方案一個簡單的錯誤被發現,我似乎被卡住:軌道4,未知的行動,該行動「摧毀」不能爲PostsController

帖子#控制器:

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 

耙路線:

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之後,我似乎得到了一些基本問題,可能是一個小小的疏漏,任何人都有什麼想法?

+1

您可以發佈您控制器的頂線和你的路由文件的相關部分? – jvperrin

+0

plz顯示,你如何從你的視角調用摧毀方法? –

回答

2

PostsController#destroy在你的private聲明之下,所以它是private method - 它有如何被調用的限制。

嘗試字private上述移動def destroy ... end(和保護該路線的另一種方法,如果合適的話)。如果由於某種原因,你仍然需要調用一個私有方法,你可以使用#send,例如:

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

(使用#send這樣沒有意義的Rails控制器,但它可能會派上用場另一個時間! )

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的,但它可能適用於其他版本。