2017-01-18 4 views
0

私はシンプルなレールアプリを作ろうとしています。ここでuseresは投稿にコメントを残すことができます。未定義のメソッド `user_name 'for nil:NilClass

新しい投稿を作成すると、undefined method 'user_name' for nil:NilClassエラーが発生します。

具体的には、以下:

error page

あなたが写真で見ることができるように、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 

感謝。申し訳ありませんが、文法上の誤りは、私はこれに取り組んでいたし、私が目を覚ましているときに素晴らしいスペルラーではありません。

+0

すべての既存のレコードにuser_idがありますか?これをコンソール 'Comment.where(user_id:nil).count'で試してください。0以外の場合はそれらのレコードを削除してください。 –

+0

既存のレコードにはidsがありませんComment.allはオブジェクトに戻ります。 – Jones

答えて

0

その投稿のコメントの1つにユーザーがない可能性があります。ここでtryメソッドを使用できます。

@comment.try(:user).try(:user_name) 

しかし、将来の任意のユーザーが作成したすべてのコメントは、名前になりますように、ユーザーモデルに存在検証を追加することですこれを処理するための理想的な方法。

+0

@ ZhongZheng答えはスポットです! –

+0

私のコメントモデルは現在 'validates:user_id、presence:true'(所属に加えて)があります。 – Jones

1

のtry変更

@comment.user_id = current_user.id 

あなたはcommentは、ユーザー/ user_idをせずに保存されません、またはビューにケースを処理する必要があることを確認するか必要

@comment.user = current_user 

にどこのユーザー/ user_idはゼロです

+0

コメントに必要なデータが保存されていることを確認するにはどうすればよいですか? 'comment_params'は現在' params.require(:comment、:user_id).permit(:content) 'のようになりますが、まだエラーが出ます。なぜ@ post.commentsには何か要素がありますか? – Jones

+0

それは以下のようになります: 'params.require(:comment).permit(:content、:user_id)' –

1

あなたの名前を尋ねていますが、あなたのcomment_paramsに現在user_idは許可されていません:

この:

def comment_params 
    params.require(:comment).permit(:content) 
end 

は次のようになります。

def comment_params 
    params.require(:comment).permit(:content, :user_id) 
end 

あなたのコードがなければならないことも可能である:

comment.user.name 

代わりの

comment.user.user_name 

あなたのモデルを確認して確認する必要があります。私はuserの属性としてuser_nameを使用しません。

+0

メソッド名に問題があった場合。なぜNilを取得するのでしょうか?NilClassエラー?問題は、変数の1つを除いてすべてがnilであるコメントを作成していることです。 – Jones

関連する問題