【发布时间】: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 添加
<p><%= @article.comments.pluck(:id) %></p>给了我一个与 [5] 相关的信息。为那篇文章创建附加评论将该行更改为 [5,9]。当然,我必须删除 @article.cmets.size 才能显示采摘线。
标签: ruby-on-rails ruby