2014-04-07 20 views
1

我是RoR的初學者(8小時大),面臨着我無法逾越的問題。在他們網站上的入門指南中介紹的教程通過設置帖子輸入示例。我得到以下錯誤:Ruby on Rails錯誤顯示發佈時間

NoMethodError in Posts#show 
Showing /Users/khalidalghamdi/blog/app/views/posts/show.html.erb where line #3 raised: 

undefined method `title' for nil:NilClass 
Extracted source (around line #3): 
1 
2 
3 
4 
5 
6 

    <p> 
    <strong>Title:</strong> 
    <%= @post.title %> 
    </p> 

    <p> 

Rails.root: /Users/khalidalghamdi/blog 

Application Trace | Framework Trace | Full Trace 
app/views/posts/show.html.erb:3:in `_app_views_posts_show_html_erb__4427112910992919114_2164032300' 
Request 

Parameters: 

{"id"=>"4"} 

,這是教程鏈接http://guides.rubyonrails.org/getting_started.html和我下面第5.6節。它沒有在show.html.erb頁面中顯示發佈的詳細信息。我究竟做錯了什麼?

更新:控制器代碼:

class PostsController < ApplicationController 
    def new 

    end 

    def create 
     @post = Post.new(post_params) 

     @post.save 
     redirect_to @post 
    end 

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


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


end 
+0

你可以發佈你的控制器代碼嗎? – Pavan

+0

@Pavan添加到問題 – spacemonkey

+0

@spacemonkey檢查我更新的答案。 –

回答

7

設置實例中PostsController#show操作變量@post。 目前,@post變量設置爲零所以你得到undefined method 'title' for nil:NilClass錯誤。

private中刪除show操作。它沒有被調用,因爲你已經把它變成了私人的。因此未設置@post

例如:(由於您沒有共享的代碼,我給一個例子)

class PostsController < ApplicationController 
    ## ... 
    def show 
    @post = Post.find(params[:id]) 
    end 
    ## ... 

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

此外,更好的方法是在你的控制器中添加before_action在這裏你可以設置@post變量以避免跨多個操作的冗餘代碼。這也使你的代碼DRY

例如:

class PostsController < ApplicationController 
    ## set_post would be called before show, edit, update and destroy action calls only 
    before_action :set_post, only: [:show, :edit, :update, :destroy] 
    ## ... 

    def show 
    ## No need to set @post here 
    end 

    ## .. 
    private 

    def set_post 
    @post = Post.find(params[:id]) 
    end 

    def post_params 
     params.require(:post).permit(:title, :text) 
    end 
end 
+0

非常感謝,引導良好。 – spacemonkey

+1

+1 for'before_action' :) – Pavan

+0

@spacemonkey很高興幫助:) –

1

看到你的控制器代碼,您已經定義了private方法後,您show行動。

把它上面的私有方法這樣

class PostsController < ApplicationController 
    def new 

    end 

    def create 
     @post = Post.new(post_params) 

     @post.save 
     redirect_to @post 
    end 

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

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

end 

注:

定義後的私有方法也作爲private處理任何方法。

+0

謝謝你的工作 – spacemonkey