I am following Jumpstartlab's Blogger Rails tutorial.
I am using Ruby 2.2.1 and Rails 4.0.0.
The "undefined method 'name' for nil:NilClass" error is raised when I add
(<%= @article.comments.size %>)
to
<h3>Comments</h3>
in ~/show.html.erb.
If I swap this line with
<%= 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).
I tried git hard reset
to restore the entire comments section and redo all of it, but I got the same error.
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?"} %>
I am using...
articles.rb:
class Article < ActiveRecord::Base
has_many :comments
end
comment.rb:
class Comment < ActiveRecord::Base
belongs_to :article
end
My fix is to swap
<h3>Comments (<%= @article.comments.size %>)</h3>
with
<%= 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
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.
<%= @article.comments.pluck(:id) %>
` gave me a line with [5]. Creating an additional comment for that article changed that line to [5,9]. Of course, I had to remove @article.comments.size to be able to display the pluck line. – Jean Merlet Jan 23 '16 at 17:46<%= @article.comments.pluck(:id) %>
` to be `<% testx = @article.comments.size %>` (notice no "="). Then new line `<%= testx %>
`. Do you see a size now? – rdnewman Jan 23 '16 at 20:38