2017-04-26 77 views
-2

通常博客渲染的部分意見文件,即PostsComments ...有麻煩後的節目頁面

評論屬於帖子...

帖子控制器是朝着面向所有典型動作帖子。

帖子模式has_many評論

帖子觀點表示了罰款...

然後創建評論控制器,型號,只有兩個局部視圖文件,即_form.html.erb_comment.html.erb ...

在郵政show.html.erb,我把他們兩個這樣的:

<h2>Recent Comments</h2> 

<%= render @comment.comments %> 

<h2>Add Comments</h2> 

<%= render 'comments/form' %> 

當我遇到這樣的麻煩,即得到這個錯誤,當我點擊後的節目鏈接,該鏈接...我得到這個錯誤:

NoMethodError in Posts#show & undefined method意見對零:NilClass in reference to this line <%=渲染@comment。評論%>`,我不知道如何解決它...

郵政的控制器

class PostsController < ApplicationController 


    def index 
     @posts = Post.all 

     if @posts.blank? 
      flash[:alert] = "No posts have been created." 
     else 
      @posts 
     end 
    end 

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

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

     if @post.update(post_params) 
      flash[:notice] = "Post has been updated." 
      redirect_to @post 
     else 
      flash.now[:alert] = "Post has not been updated." 
      render "edit" 
     end 
    end 

    def create 
     @post = Post.new(post_params) 

     if @post.save 
      flash[:notice] = "Post has been created." 
      redirect_to @post 
     else 
      flash[:notice] = "Post has not been created." 
     end 
    end 

    def new 
     @post = Post.new 
    end 

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

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

     flash[:notice] = "Post has been deleted." 
     redirect_to posts_path 
    end 


    private 

    def post_params 
     params.require(:post).permit(:title, :author, :body) 
    end 

end 

評論控制器

class CommentsController < ApplicationController 


    def create 
     @post = Post.find(params[:post_id]) 
     @comment = @post.comments.create(comment_params) 
     redirect_to post_path(@post) 
    end 


    private 

     def comment_params 
      params.require(:comment).permit(:author, :body) 
     end 
end 

評論_comment.html.erb

<p> 
    Author: 
    <%= comment.author %> 
</p> 
<p> 
    Body: 
    <%= comment.body %> 
</p> 

請讓我知道,如果需要進一步的資料。

回答

2

注意什麼你的錯誤是想告訴你:

NoMethodError in Posts#show undefined method 'comments' for nil:NilClass regarding <%= render @comment.comments %>

這是告訴你,有沒有爲NilClass方法comments。那意味着@comment是零。 @comment爲零,因爲您從未在各自的Posts#show操作中定義該變量。在那裏,你只有一個@post變量。

我的猜測是,你實際上意味着做的是:<%= render @post.comments %>

+0

用'<%= @ post.comments%>',我得到這個錯誤:'未定義的方法的意見對零:NilClass' – user273072545345

+0

所以,基於錯誤,這意味着我需要在'Posts#show'操作中插入一些有關注釋的內容? – user273072545345

+0

好的,讓我們繼續調試。 *爲什麼*是'@ post'零? – Brennan