如何添加评论

时间:2013-06-07 14:02:36

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

我正在尝试为帖子模型添加评论。到目前为止,这是我的comments_controller:

class CommentsController < ApplicationController

    before_action :find_post

    def index
        @comments = @post.comments.order('id')
    end

    def new
        @comment = @post.comments.new
    end

    def create
        @comment = @post.comments.build(params[:comment])
        @comment.user = current_user
        @comment.save
        redirect_to post_path(@post)
    end

    private
    def comment_params
        params.require(:comment).permit(:comment_body)
    end

    def find_post
        @user = current_user
        @post = @user.posts.find(params[:post_id])
    end
end

我收到此错误:

   CommentsController中的NoMethodError #new undefined方法`posts'for   零:NilClass

你可以看到我是编程的新手。谢谢你的帮助!:)

1 个答案:

答案 0 :(得分:1)

当您未登录时,可能会收到错误。由于find_post,每次都会调用方法before_action :find_post。如果您尚未登录,则current_usernil,并致电posts nil