Rails“未定义方法”未评估的循环内错误
此代码工作正常(使用 HAML):
#comments
- @blog.comments.each do |comment|
.comment
.username
- if !eval("comment.user").nil?
#{comment.user.email}
.content
#{comment.content}
但是,如果我删除“eval”行,即
#comments
- @blog.comments.each do |comment|
.comment
.username
#{comment.user.email}
.content
#{comment.content}
我收到错误:
undefined method `email' for nil:NilClass
即使数据库中没有注释(因此不应评估循环内容)。到底是怎么回事?
This code works properly (using HAML):
#comments
- @blog.comments.each do |comment|
.comment
.username
- if !eval("comment.user").nil?
#{comment.user.email}
.content
#{comment.content}
However, if I remove the "eval" line i.e.
#comments
- @blog.comments.each do |comment|
.comment
.username
#{comment.user.email}
.content
#{comment.content}
I get an error:
undefined method `email' for nil:NilClass
Even when there are no comments in the database (hence the loop contents should not be evaluated). What is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试以下操作:
我认为问题是您强制 ruby 使用 #{comment.user.email} 评估 comment.user.email。
在控制台中尝试一下:
它会失败,因为除以 0,但 param 为 nil。
Try the following:
I think the problem is that you are forcing ruby to evaluate comment.user.email with #{comment.user.email}.
Try this in the console:
It will fail because of a division by 0, but param is nil.
啊,问题解决了!
问题是在发布的代码上方,我有一行:
当我将该表单移到循环下方时,错误消失了。
Ah, problem solved!
Issue was that above the posted code, I had the line:
When I moved that form below the loop the error disappeared.