Home>

There are User model and Message model, and they are related as follows.

# user.rb
has_many: send_messages, class_name: "Message", foreign_key: "send_user_id", dependent:: destroy
has_many: recive_messages, class_name: "Message", foreign_key: "recive_user_id", dependent:: destroy;
# message.rb
belongs_to: send_user, class_name: "User", foreign_key: "send_user_id", optional: true
belongs_to: recive_user, class_name: "User", foreign_key: "recive_user_id", optional: true


I also confirmed that it can be associated and called firmly on the console in this way.
However, it cannot be called with the following code.

# users.controller
def show
    @user = User.find_by (id: params [: id])
    @recive_messages = @ user.recive_messages.order (id: "DESC")
    @send_messages = @user .send_messages.order (id: "DESC")
end
# users/show.html.erb
<% @ recive_messages.each do | message |%>
#Image upload uses carrierwave
<% = message.send_user.profile_image.url%>
<% = message.send_user.username%>
<% end%>


Both can be called on the console, but in view I get a NomethodError.

Thanks for your cooperation.

  • Answer # 1

    It seems that an error occurred when there was no user belonging to message without logging in because it was possible to post even when message was not logged in.
    I was able to solve it if I made a conditional branch firmly