i have a User model and a UserMessage model (a model for holding the private messages between two users)
in my view i have..
<% if @message_items.any? %>
<ol class="messages">
<%= render partial: 'message_item', collection: @message_items%>
</ol>
<%= will_paginate @message_items %>
<% end %>
which i render with…
<li id="<%= message_item.id %>">
<span class="user">
<%= link_to message_item.user.name, message_item.user %>
</span>
<span>
<%= message_item.title %>
</span>
<span>
<%= message_item.body %>
</span>
</li>
how is the object UserMessage(which is coming from message_item) able to render the User object? my design for the UserMessage just has the following attributes “id, user_id, from_id, title, body, created_at, updated_at”.
i guess its from the user_id, and rails somehow makes the connection and is able to find the User object from the user_id. is that correct?
but i what i really want though, is the user from the from_id (the person sending the message). is there a way to retrieve that? i know doing something like.. message_item.user.from_id does not work.
the only way i could think of that works is by doing
<%= User.find(id= message_item.from_id).name %>
but that doesn’t seem right putting so much code in my view. sorry but ive been super stuck. help would be much appreciated. thanks
i think you are looking for foreign_key option for belongs_to in model. So what you need is to specify something like sender/from relation with from_id in UserMessage message
Then in template you just call this relation in view.
It should work same as
message_item.user.For further reference visit documentation for associations
In addition i recommend you not call
.namemethod in template, but specify to_s method in your model. Good approach pointed by klump in his answer is to use.includemethod for better performance. It will load user data while loadingUserMessagedata, not in another query.Code was derived from another answer — Rails ActiveRecord: Is a combined :include and :conditions query possible?