未定义的方法`电子邮件”的零:NilClass在Exibe表父亲的邮件(undefined meth

2019-07-17 20:51发布

我有一个问题,我有这样的atribbuition我的评论模型:

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

这在用户模型

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

但不要的工作原理:

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

出现错误:

undefined method `email' for nil:NilClass

请有什么问题,在创建评论我做出atribbuition这样的,请看:

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

我该如何解决这个错误,求你

更新下的反应,错误PERSISTES:

我试试这个:

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

这个

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

还有这个:

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

不工作

同样的错误:

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%>

我不知道什么是错我的模型评论有:USER_ID

  attr_accessible :comment,:user_id,:post_id

和我的形式作是这个

   <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 %>

请帮助我,我不知道哪里是错误,DB是正确迁移

Answer 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))

但接下来会更好(:user_id是不是为大众分配访问):

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


Answer 2:

如果您在日志中看看,你可能会看到有关尝试指派USER_ID警告。 如果你要使用attr_accessible那么你需要添加所有你想要分配的属性。 更改

  attr_accessible :comment

  attr_accessible :comment,:user_id


Answer 3:

怎么样

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


文章来源: undefined method `email' for nil:NilClass in Exibe the mail of table Father