【问题标题】:Rails "undefined method 'name' for nil:NilClass" error when adding @article.comments.size添加@article.comments.size时Rails“nil:NilClass的未定义方法'名称'”错误
【发布时间】:2016-01-23 17:26:50
【问题描述】:

我正在关注 Jumpstartlab 的 Blogger Rails 教程。

我正在使用 Ruby 2.2.1 和 Rails 4.0.0。

添加时出现“nil:NilClass 的未定义方法 'name'”错误

(<%= @article.comments.size %>)

<h3>Comments</h3>

在 ~/show.html.erb 中。

如果我把这一行换成

<%= render partial: 'articles/comment', collection: @article.comments %>

我没有收到任何错误,一切都显示正确(除了标题显示在错误的位置 - 在 cmets 之后,而不是之前)。

我尝试git hard reset 恢复整个 cmets 部分并重做所有部分,但我得到了同样的错误。

这是我的 ~/show.html.erb 代码,当它引发错误时:

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<h3>Comments (<%= @article.comments.size %>)</h3>
<%= render partial: 'articles/comment', collection: @article.comments %>
<%= render partial: 'comments/form' %>
<%= link_to '<< Back to Articles List >>', articles_path %>
<%= link_to 'edit', edit_article_path(@article) %>
<%= link_to 'delete', article_path(@article), method: :delete, data: {confirm: "Really delete the article?"} %>

我正在使用...

articles.rb:

class Article < ActiveRecord::Base
  has_many :comments
end

comment.rb:

class Comment < ActiveRecord::Base
  belongs_to :article
end

我的解决方法是交换

<h3>Comments (<%= @article.comments.size %>)</h3>

<%= render partial: 'articles/comment', collection: @article.comments %>

但这会在错误的位置显示标题。为什么这行得通对我来说也没有任何意义。请注意,如果我不包含,则没有错误

(<%= @article.comments.size %>)` in `<h3>Comments

NoMethodError undefined method `name' for nil:NilClass)”的解决方案使我检查了我的数据库中是否存在丢失的 ID,但那里没有问题。

【问题讨论】:

  • 我看不到你在哪里打电话给name
  • 使用你想要的命令顺序,当你在有问题的两行之间添加这一行时会发生什么:p @article.comments.pluck(:id)?它会让你的页面有点混乱(它只是为了帮助诊断),但你应该会看到页面上显示的一组 id。如果不是这样,那可能有助于我们弄清楚你在做什么。
  • @rdnewman 添加&lt;p&gt;&lt;%= @article.comments.pluck(:id) %&gt;&lt;/p&gt; 给了我一个与 [5] 相关的信息。为那篇文章创建附加评论将该行更改为 [5,9]。当然,我必须删除 @article.cmets.size 才能显示采摘线。
  • 是的,这是一个 Rails 版本问题(或 ruby​​ 版本问题,取决于你如何看待它)。我最初的搜索不足以找到这个解决方案。正如here 建议的那样,升级到 Rails 4.1.2 时一切正常。虽然我相信this 是对这个问题的更全面的讨论。但是,我不相信这些解决方案是在 SO 上的。
  • 嗯,这似乎和这两个 SO 解决方案是同一个问题:onetwo。但是,我收到的错误消息根本没有提到 ActiveRecord 或 has_many 关联,所以我不知道将其输入到我的搜索中。

标签: ruby-on-rails ruby


【解决方案1】:

您可以尝试使用.count.length 而不是.size

<h3>Comments (<%= @article.comments.count %>)</h3>

我使用的是 ruby​​ 2.3 和 rails 4.0.0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2013-07-16
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多