Home>

Added the ability to comment on articles in Ruby on Rails5.
Checking the show page with no comment data, @ entry.comments.size is
It is set to 1 in the initial state, and an error occurs in the comment.user.name part of partial.
I also checked the rails console, but the number of comments was 0.
Thanks for your professor.

<% = @ entry.comments.size%>#Displays 1 here.
<% = render: partial =>"comments/comment",: collection =>@ entry.comments%>
2.3.0: 006>Comment.all
  Comment Load (0.2ms) SELECT "comments". * FROM "comments" LIMIT? [["LIMIT", 11]]
 =>#<ActiveRecord :: Relation []>
2.3.0: 010>comments.size
   (0.3ms) SELECT COUNT (*) FROM "comments" WHERE "comments". "Entry_id" =? [["Entry_id", 1]]
 =>0
<% = comment.user.name%>
 <% = comment.body%>
class Comment<ApplicationRecord
  belongs_to: user
  belongs_to: entry
  validates: body, presence: true
end

class Entry<ApplicationRecord
  belongs_to: podcasts
  has_many: comments
end
  • Answer # 1

    size includes unsaved records.
    Is the process like@ enty.comments.newor@ enty.comments.buildconfused by the controller?
    I think that it is an error because user is empty in the comment before saving after building.

Related articles