i have a user model and a message model. my user has_many messages and my message belongs_to user.
on my message model, i have the attributes :content, :user_id, :to_id.
the :user_id acts as the foreign key, and can also be thought of as the ‘sender’ while the :to_id can be thought of as the ‘receiver’.
in my message index template, when im trying to display all the messages, i do something like…
<%= link_to message_item.user.name, message_item.user %>
that line works great when showing my received messages (where im the :to_id and :user_id is showing who sent me the message)
however, when im listing the messages under my ‘sent’ category, doing the line of code above will always show my name (because im :user_id) as opposed to the :to_id, which would make more sense.
ideally i would want something like
<%= message_item.to_id %>
for my sent category. is there a way to get the user object mentioned in my :to_id category?
something like message_item.to_id.name wouldn’t work because message_item.to_id returns back an integer and not the user object. is there a way to get it?
at trying to display and linking to the sender, here is my failed attempt
<% if current_user == message_item.user %>
<%= message_item.to_id %>
<% else %>
<%= link_to message_item.user.name, message_item.user %>
<% end %>
thanks
What you need to do is define the relationship for the receiver in
message.rb:I find it’s usually more clear if you call things like
to_idto beto_user_idso it’s clear that you’re talking about a user and not something else.Now you can call: