0

投稿モデルにコメントを追加しようとしています。これまでのところ、これは私の 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#nil:NilClass の新しい未定義メソッド「posts」

ご覧のとおり、私はプログラミングが初めてです。手伝ってくれてありがとう!:)

4

1 に答える 1

1

サインインしていないときにエラーが発生する可能find_post性がありますbefore_action :find_post。サインインしていない場合current_userはであり、をnil呼び出します。postsnil

于 2013-06-07T14:19:10.377 に答える