Reputation: 3281
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
Upvotes: 0
Views: 239
Reputation: 2803
This is funny, I answered a similar question today.
First, you must set your Message
and User
models like this.
So, for your sent messages, you can use:
<%- current_user.messages.each do |message| -%>
<%= link_to message.recipient.name, user_path(message.recipient) %>
<%- end -%>
And for the received messages:
<%- current_user.messages_received.each do |message| -%>
<%= link_to message.user.name, user_path(message.user) %>
<%- end -%>
That should be enough.
Upvotes: 1
Reputation: 211560
What you need to do is define the relationship for the receiver in message.rb
:
belongs_to :to,
:class_name => 'User',
:foreign_key => :to_id
I find it's usually more clear if you call things like to_id
to be to_user_id
so it's clear that you're talking about a user and not something else.
Now you can call:
<%= link_to(message.to.name, message.to) %>
Upvotes: 2