2015-12-19 57 views
-1
當我試圖對帖子@comment輸出用戶FIRST_NAME

/show.html.erb我得到這個錯誤未定義的方法`FIRST_NAME」的零:NilClass無法顯示用戶名

comments_controller.rb

class CommentsController < ApplicationController 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(comment_params) 
    @comment.user_id = current_user.id 
    @comment.save 
    redirect_to post_path(@post) 
    end 

    def new 
    @comment = Comment.new 
    end 

    def show 
    @comment = Comment.find(params[:id]) 
    end 

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

    private 

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

的意見/ _show.html.erb

<% @post.comments.each do |comment| %> 
<h3><%= comment.body %></h3> 
<h6><%= comment.user.first_name %></h6> 
<% end %> 

個我帖子/ show.html.erb

<div class="show_post"> 
    <h1><%= @post.title %></h1> 
    <p>Created <%= time_ago_in_words(@post.created_at) %> ago | 
    <%= link_to 'Edit', edit_post_path %> 
    | 
    <%= link_to 'Delete', '#' %> 
</p> 
<div class="body"> 
    <p><%= @post.body %></p> 
</div> 
<hr> 

<div id="comments"> 
    <%= render 'comments/show' %> 
    <%= render 'comments/new' %> 
    </div> 
+1

是current_user nil? – eeeeeean

+0

在控制檯我有** user_id **,但爲什麼我不能在視圖上顯示? #]> –

+0

請評論has_many用戶嗎? – Doon

回答

0

是在current_user法正常工作?在認證過程後嘗試刪除byebug並查看當前用戶(通過在控制檯中鍵入current_user)。

嘗試使用current_user.comments.build(comment_params),並在您的posts_controller.rb將這些行添加到show操作中。

def show 
    @post = Post.find(params[:id]) 
    @comment = Comment.new 
    @comment.post = @post 
end 
+0

current_user正常工作,但你的提示沒有幫助我 –

0

你能把byebug在show.html.erb和_show.html.erb並檢查comment.user存在?