1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コメントの投稿者名を表示したい

Posted at

User,Post,Commentの3つのリレーションが、以下の時にコメント一覧でコメントの投稿者名を表示させたい。

user.rb
has_many :posts
has_many :comments
post.rb
belongs_to :user
fas_many :comments
comment.rb
belongs_to :user
belongs_to :post
show.html.erb
<p>コメント一覧</p>
<% @comments.each do |c| %>
    <hr>
    <a href="/users/#{c.user_id}"><%= c.user.name %></a>
    <%= c.content %>
<% end %>

c.user.nameのnameがNoMethodErrorとなるので、posts.controllerに以下の1行追加することでcommentに関係したuserの情報を取り入れることができる。

posts.controller.rb
def show
   @comments = @post.comments.includes(:user).all
end
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?