2

我有一个问题,我把这个归因于我评论模型:

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

请问有什么问题,在创建评论时我做出了属性,请看:

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

我如何解决这个错误,请-

更新下一个响应,错误仍然存​​在:

我试试这个:

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

请帮助我,我不知道错误在哪里,数据库已正确迁移

4

3 回答 3

0

如果您查看日志,您可能会看到有关尝试分配 user_id 的警告。如果您要使用 attr_accessible 那么您需要添加您希望分配的所有属性。改变

  attr_accessible :comment

  attr_accessible :comment,:user_id
于 2013-01-05T20:13:08.337 回答
0
# 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
于 2013-01-05T22:12:05.170 回答
0

怎么样

@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.post = @post
@comment.save
于 2013-01-05T22:29:15.340 回答