NoMethodError"nil的未定义方法`email':NilClass"

Jon*_*son 2 ruby-on-rails

在我的一个观点中,我遇到以下代码的问题:

<% @blog.comments.each do |comment| %>
<h3><%= comment.user.email %></h3>
</div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

哪个产生错误:

NoMethodError in Blogs#show
...
undefined method `email' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

但是以下代码可以正常运行:

<% @blog.comments.each do |comment| %>
<%= comment.body %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

评论声明为:

class Comment < ActiveRecord::Base
  belongs_to :blog
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

并且可以在另一个视图中访问email属性:

<% @users.each do |user| %>
  <tr>
    <td><%= link_to user.username, user %></td>
    <td><%= user.email %></td>
  </tr>
<% end %>
Run Code Online (Sandbox Code Playgroud)

对我来说,它看起来像comment.user没有被承认为用户模型的实例.我究竟做错了什么?

Ted*_*ddy 8

comment.user在尝试调用方法之前,您需要检查是否为nil.一个if语句可以为你做这个:

<% @blog.comments.each do |comment| %>
  <h3><%= comment.user.email if comment.user %></h3>
  </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 更合适的是,您可能需要确保在没有用户的情况下不存在评论,使用验证或沿着这些行进行评论.上面的代码将阻止错误显示,但我认为你所看到的是应用程序中管理数据的更大失败的症状. (5认同)