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

放肆的年华 提交于 2019-12-01 08:54:43

问题


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


来源:https://stackoverflow.com/questions/14175913/undefined-method-email-for-nilnilclass-in-exibe-the-mail-of-table-father

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!