I want to display the name of the poster of the comment in the comment list when the three relations of User, Post, and Comment are as follows.
user.rb
has_many :posts
has_many :comments
post.rb
belongs_to :user
fas_many :comments
comment.rb
belongs_to :user
belongs_to :post
ruby:show.html.erb
<p>List of comments</p>
<% @comments.each do |c| %>
<hr>
<a href="/users/#{c.user_id}"><%= c.user.name %></a>
<%= c.content %>
<% end %>
Since the name of c.user.name becomes NoMethodError, the user information related to comment can be incorporated by adding the following line to posts.controller.
ruby:posts.controller.rb
def show
@comments = @post.comments.includes(:user).all
end
Recommended Posts