undefined method `email' for nil:NilClass in E

2019-02-19 07:14发布

问题:

I have a problem, i make this atribbuition i comment model:

class Comment < ActiveRecord::Base
  attr_accessible :comment
  belongs_to :post
  belongs_to :user

and this in user model

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  has_many :posts
  has_many :comments

but this dont works:

  <% post.comments.each do |comment|   %>
    <div id="comments" >
      <%= comment.user.email %>
           <%= comment.comment %>
    </div>
   <%end%>

appear the error:

undefined method `email' for nil:NilClass

please what is the problem, in the create of the comment i make the atribbuition so , look:

  @comment = @post.comments.create(params[:comment],:user_id => current_user.id)

how i solve this error, please-

UPDATE NEXT RESPONSES, THE ERROR PERSISTES:

I try this:

@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.post = @post
@comment.save

this

@comment = @post.comments.create(params[:comment].merge(:user_id => current_user.id))

and this:

@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save

dont works

same error:

undefined method `email' for nil:NilClass
Extracted source (around line #48):

45: 
46:       <% post.comments.each do |comment|   %>
47:         <div id="comments" >
48:           <%= comment.user.email %>
49:                <%= comment.comment %>
50:         </div>
51:        <%end%>

i dont know what is wrong my model comment have :user_id

  attr_accessible :comment,:user_id,:post_id

and my form make is this

   <div id="comment_form_<%= post.id %>" style="display: none;" >

      <%= form_for [post,post.comments.build], :remote => true,:class=>"comment" do |com| %>
          <%= com.text_area :comment %>
          <%= com.submit "aaa" %>

      <%end %>

please help me i dont know where is the error, the db is migrate correctly

回答1:

# Model
class Comment < ActiveRecord::Base
  attr_accessible :comment, :user_id
end

#Controller
@comment = @post.comments.create(params[:comment].merge(:user_id => current_user.id))

But next would be better (:user_id is not accessible for mass-assignment):

@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save


回答2:

If you look in the log you will probably see a warning about trying to assign user_id. If you are going to use attr_accessible then you need to add all the attributes that you wish to assign. Change

  attr_accessible :comment

to

  attr_accessible :comment,:user_id


回答3:

How about

@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.post = @post
@comment.save