Home>

I'm currently creating a posting app on rails.
An app where two people (user, coach) can send comments, images, and videos in a room, and want to display the sender's name next to the post to determine who sent it in the room. is. Currently, the current_user.name is displayed, so the name of the person who is logged in is displayed.

Since I have an association with comment, I thought that comment.user.name would solve it, but I got an error.

Rails beginners can't solve it. Thanks for your support.

NoMethodError in Comments # index
undefined method `name'for nil: NilClass
<% if user_signed_in?%>
  <% @ comment.each do | comment |%>
     <% = comment.user.name%><br><-This is the part
    <% = comment.content%>
    <% = l comment.created_at%><br>
    <% if comment.image.attached?%>
View file
<% If user_signed_in?%>
  <% @ comment.each do | comment |%>
     <% = comment.user.name%><br>
    <% = comment.content%>
    <% = l comment.created_at%><br>
    <% if comment.image.attached?%>
      <% = image_tag comment.image.variant (resize: '500x500')%><br>
    <% end%>
    <% if comment.video.attached?%>
      <video src = "<% = rails_blob_path (comment.video)%>", type = "video/mp4" controls></video><br>
    <% end%>
  <% end%>
<% else coach_signed_in?%>
  <% @ comment.each do | comment |%>
     <% = comment.coach.name%><br>
    <% = comment.content%>
    <% = l comment.created_at%><br>
    <% if comment.image.attached?%>
      <% = image_tag comment.image.variant (resize: '500x500')%><br>
    <% end%>
    <% if comment.video.attached?%>
      <video src = "<% = rails_blob_path (comment.video)%>", type = "video/mp4" controls></video><br>
    <% end%>
  <% end%>
<% end%>
What I tried

The cause of the error is
The user and coach are linked to the comment, but it was because I was trying to get information from the comment posted when the user logged in, even when I logged in with coach. (Comment.coach.name is displayed when you post and log in with coach, but when you log in as user, the view is comment.user.name, so i am trying to retrieve coach information from user. Please check the code of the view file.) * Sorry for the poor text. Please comment if you do not get it.

If i have any better code to solve, I would appreciate it if you could let me know.

Supplementary information (FW/tool version, etc.)

If i have any missing or interesting code, please leave a comment.

  • Answer # 1

    The description of conditional branching was added as follows.

    <% if comment.coach_id.present?%>
    <% = comment.coach.name%>
    <% else%>
    <% = comment.user.name%>
    <% end%>

    The coach's name was displayed if the coach_id was present, and the user's name was displayed if the coach_id was nil.
    Thank you to everyone who read my post.