I have a User class with a has_many :messages and a Message class which belongs_to :user. In the Message controller’s show action has the corresponding view:
<% if @messages.any? %>
<ol class="microposts">
<%= render partial: 'shared/message', collection: @messages %>
</ol>
<% end %>
And the shared/_message.html.erb template looks like this:
<li id="<%= message.id %>">
<span class="content"><%= message.body %></span>
<% user_id = message.from %>
<% user = User.find(user_id) %>
From: <%= user.name %>
</li>
I feel like the following two lines should be done in the Messages controller from what I read in tutorials on Rails:
<% user_id = message.from %>
<% user = User.find(user_id) %>
But how would I pass each message’s corresponding from value (which stores user.id) into the partial?
thanks,
mike
So far i have understood that you have a
fromcolumn in yourmessagestable which stores theuser_id. So if you callmessage.fromit returns theuser_id. Then you can do the followingIn your controller
Now in your view you can call
message.user.nameto get the user’s name directly. You dont need these following two lines in your view at all<% user_id = message.from %>
<% user = User.find(user_id) %>
Let me know if ive missed anything.
UPDATE:
Here is what Ive tried with
User Model
Message Model
Now say
p1is sending a message top2Now for a
message, you can get bothsenderandreceipentdirectly like