Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTrent Janckila
4,749 Points@post.comments.length is 1 when no comments exist
I'm attempting to add/edit comments added to the blog site that has been being created, and I keep having a strange error.
Even though there are no comments associated with a post, the post still has a comments array of length 1. This means that when attempting to render the post page (or render any page that includes the comment partial), rails attempts to render a comment with a comment_id = nil. As one might expect, this plays merry havoc with my attempts to put the blog together.
I came across another question ( https://teamtreehouse.com/community/no-route-matches-actionedit-controllercomments-idnil-postid2-missing-required-keys-id ), which I assume has the same problem, but there was no resolution.
Where would one start looking to discover this mystery element?
TLDR version: Rails is showing an extra element in all post comments which is breaking the blog app.
1 Answer
Trent Janckila
4,749 PointsI found the issue. I was creating a new comment form to display before the comments were being displayed on the page. This was creating the empty comment causing problems a few lines later when it grabbed all comments associated with the post. I've changed it for now so I'll be able to continue through the course, but I'd prefer to be able to have the "add a comment" form before the comments.
before (how I'd like it)
<div id="comments">
<h1>Comments</h1>
<h2>Add a Comment</h2>
<%= render partial: "comments/form", locals: {comment: @post.comments.new} %>
<% @post.comments.each do |comment| %>
<%= render partial: "comments/comment", locals: {comment: comment} %>
<% end %>
</div>
After (now working)
<div id="comments">
<h1>Comments</h1>
<% @post.comments.each do |comment| %>
<%= render partial: "comments/comment", locals: {comment: comment} %>
<% end %>
<h2>Add a Comment</h2>
<%= render partial: "comments/form", locals: {comment: @post.comments.new} %>
</div>
Trent Janckila
4,749 PointsTrent Janckila
4,749 PointsTo add on some more to this, the mystery length does not appear in the rails console.
The mystery array element only appears when accessing the comments from the rails blog. Here's the logging from the rails log.