【发布时间】:2015-07-07 02:58:56
【问题描述】:
首先,我只想说我以前遇到过这个问题,通常可以快速解决。但这次我真的很困惑。
我有一个简单的发布应用程序,用户可以在其中发布状态/图像。我添加了添加 cmets 的功能,但这是我遇到的问题:
在我的帖子显示页面上,我列出了所有 cmets,以及添加新评论的能力。
帖子展示页面:
<%if @post.is_status?%>
<h5><%=@post.user.email%>:</h5>
<%=@post.body%><br>
Posted:<%=@post.created_at%><br><hr>
<%else%>
<h5><%=@post.user.email%>:</h5>
<%=image_tag @post.body%><br>
Posted:<%=@post.created_at%><br><hr>
<%end%>
<h6>Comments:</h6>
<%@comments.each do |x|%>
<%@user = x.user%>
<%=x.comment%> -<%=@user.email%> <br>
<%end%>
<%=form_for @comment do |x| %>
<%=x.hidden_field :post_id%>
<%=x.hidden_field :user_id%>
<%=x.label :comment%>
<%=x.text_area :comment%><br>
<%=x.submit%>
<%end%>
我的帖子在帖子控制器中显示操作:
def show
@post = Post.find(params[:id])
@comments = @post.comments.all
@comment = @post.comments.new(user_id: current_user.id)
end
最后是我在 cmets 控制器中的创建操作:
def create
@comment=Comment.create(params.require(:comment).permit(:comment, :post_id, :user_id))
if @comment.save
redirect_to root_path, notice: "saved"
else
redirect_to root_path, notice: "not saved"
end
end
当请求通过时,我从 rails 日志中得到以下信息:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lOHcmJJ3ptDiizpt95/1xHQ4GQkcjyHsAfTHiH/23f0Rjds7pI0Ii0XzcZ3UFGCKap7jwvdl7pV8wr+8oNu+mg==", "comment"=>{"post_id"=>"22", "user_id"=>"1", "comment"=>"test123"}, "commit"=>"Create Comment"}
所以我可以看到正在传递 user_id = 1。
我的帖子显示页面的输出给了我:
comments:
test123 -#<User:0x007fad5b4311a0>
所以我可以看到用户在那里! 如果我像这样修改我的帖子显示页面:
<%=x.comment%> -<%=@user.inspect%> <br>
我得到以下输出:
test123 -#<User id: 1, first_name: nil, last_name: nil, profile_picture: nil, created_at: "2015-07-02 03:51:14", updated_at: "2015-07-06 21:34:07", email: "test123@example.com", encrypted_password: "$2a$10$7irTux0aMTbSXZUyB3Ubbux0MBhF.Z0Ll0QyY8pS1mv...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 12, current_sign_in_at: "2015-07-06 21:34:07", last_sign_in_at: "2015-07-06 21:28:18", current_sign_in_ip: #<IPAddr: IPv6:0000:0000:0000:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>, last_sign_in_ip: #<IPAddr: IPv6:0000:0000:0000:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>>
所以我可以看到 user.email 是有效的...
但是,当我修改后显示页面时:
<%=x.comment%> -<%=@user.email%> <br>
我明白了
undefined method `email' for nil:NilClass
这很奇怪,我知道有一个用户,并且电子邮件对该用户有效,从 user.inspect 中可以看出
关于为什么它给我一个 nil 类错误的任何想法?
【问题讨论】:
-
你能发布你的完整展示页面吗?
-
刚刚发布了整页!
标签: ruby-on-rails-4 activerecord model controller rails-activerecord