Rails“未定义方法'name'为nil:NilClass"添加@article.comments.size 时出错 [英] Rails "undefined method 'name' for nil:NilClass" error when adding @article.comments.size

查看:34
本文介绍了Rails“未定义方法'name'为nil:NilClass"添加@article.comments.size 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am following Jumpstartlab's Blogger Rails tutorial.

我使用的是 Ruby 2.2.1 和 Rails 4.0.0.

I am using Ruby 2.2.1 and Rails 4.0.0.

当我添加时会引发未定义的方法 'name' for nil:NilClass"错误

The "undefined method 'name' for nil:NilClass" error is raised when I add

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

<h3>Comments</h3>

在 ~/show.html.erb 中.

in ~/show.html.erb.

如果我把这行换成

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

我没有收到任何错误,所有内容都正确显示(除了标题显示在错误的位置 - 在评论之后,而不是之前).

I get no error and everything displays correctly (except that the header displays in the wrong spot - after the comments, rather than before).

我尝试了 git hard reset 来恢复整个评论部分并重做所有内容,但我遇到了同样的错误.

I tried git hard reset to restore the entire comments section and redo all of it, but I got the same error.

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

Here is my code for ~/show.html.erb when it raises the error:

<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:

articles.rb:

class Article < ActiveRecord::Base
  has_many :comments
end

comment.rb:

comment.rb:

class Comment < ActiveRecord::Base
  belongs_to :article
end

我的解决方法是交换

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

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

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

but this displays the header at the wrong place. It also doesn't make any sense to me why this works. Note that there are no errors if I do not include

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

解决NoMethodError undefined method `name' for nil:NilClass)"让我检查我的数据库是否缺少 ID,但那里没有问题.

The solution to "NoMethodError undefined method `name' for nil:NilClass)" led me to check my databases for missing ids, but there were no problems there.

推荐答案

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

You could try using .count or .length instead of .size.

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

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

I'm using ruby 2.3 and rails 4.0.0.

这篇关于Rails“未定义方法'name'为nil:NilClass"添加@article.comments.size 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆