我正在跟随Jumpstartlab的博客园Rails教程。
我正在使用Ruby 2.2.1和Rails 4.0.0。
当我添加以下代码时,会出现“undefined method 'name' for nil:NilClass”错误:
(<%= @article.comments.size %>)
to
<h3>Comments</h3>
在~/show.html.erb文件中。
如果我把这行换成
<%= render partial: 'articles/comment', collection: @article.comments %>
我没有收到任何错误信息,所有内容都正确显示(除了标题显示在错误的位置 - 在评论之后而不是之前)。
我尝试使用git hard reset
来恢复整个评论部分并重新做一遍,但是我还是得到了同样的错误。
这是我的代码~/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?"} %>
I am using...
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 %>
但是这会在错误的位置显示标题。我也不明白为什么会有效果。请注意,如果我不包含
<header>
标签,就不会出现任何错误。(<%= @article.comments.size %>)` in `<h3>Comments
针对"NoMethodError undefined method `name' for nil:NilClass"的解决方案,引导我检查我的数据库是否缺少id,但是在那里没有任何问题。
name
。 - Andrey Deinekop @article.comments.pluck(:id)
?它会稍微弄乱您的页面(它只是用于帮助诊断),但您应该在页面上看到显示的ID数组。如果没有,那可能会帮助我们弄清楚您正在进行的操作。 - rdnewman<p><%= @article.comments.pluck(:id) %></p>
后,我得到了一行 [5]。为该文章创建一个额外的评论将该行更改为 [5,9]。当然,我必须删除 @article.comments.size 才能显示 pluck 行。 - Jean Merlet