私はシンプルなレールアプリを作ろうとしています。ここでuseresは投稿にコメントを残すことができます。未定義のメソッド `user_name 'for nil:NilClass
新しい投稿を作成すると、undefined method 'user_name' for nil:NilClass
エラーが発生します。
具体的には、以下:
あなたが写真で見ることができるように、post.comments @ nilの変数を持つ単一のコメントを含んでいるようです。
次のように私のコメント・コントローラは、次のとおりです。
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
flash[:success] = "You commented the hell out of that post!"
redirect_to @post
else
flash[:alert] = "Check the comment form, something went horribly wrong."
redicect_to @post
end
end
#...
private
def comment_params
params.require(:comment).permit(:content)
end
def set_post
@post = Post.find(params[:post_id])
end
そして、私のポストコントローラ:助けを
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :owned_post, only: [:edit, :update, :destroy]
#...
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Your post has been created!"
redirect_to @post
else
flash.now[:alert] = "Your new post couldn't be created! Please check the form."
render :new
end
end
#...
private
def post_params
params.require(:post).permit(:image, :description)
end
def set_post
@post = Post.find(params[:id])
end
感謝。申し訳ありませんが、文法上の誤りは、私はこれに取り組んでいたし、私が目を覚ましているときに素晴らしいスペルラーではありません。
すべての既存のレコードにuser_idがありますか?これをコンソール 'Comment.where(user_id:nil).count'で試してください。0以外の場合はそれらのレコードを削除してください。 –
既存のレコードにはidsがありませんComment.allはオブジェクトに戻ります。 – Jones