sending specific data into a collection partial

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 %>
<% end %>

And the shared/_message.html.erb template looks like this:

<li id="<%= %>">
  <span class="content"><%= message.body %></span>
  <% user_id = message.from %>
  <% user = User.find(user_id) %>
  From: <%= %>

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 into the partial?

thanks, mike


So far i have understood that you have a from column in your messages table which stores the user_id. So if you call message.from it returns the user_id. Then you can do the following

class Message < AR::Base
     belongs_to :user, :foreign_key=>'from' 

In your controller

@messages = Message.all.includes(:user)
#It will load messages and will associated users eager loaded.

Now in your view you can call to 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.


Here is what Ive tried with

User Model

class User < ActiveRecord::Base
    attr_accessible :age, :name
    has_many :sent_messages,    :class_name=>'Message', :foreign_key => 'from'
    has_many :received_messages,:class_name=>'Message', :foreign_key => 'user_id'
#Contains Data:
#<User id: 1, name: "p1", age: 27, ... ...>, 
#<User id: 2, name: "p2", age: 25, ... ...

Message Model

class Message < ActiveRecord::Base
    attr_accessible :body, :sender, :title, :receipent
    belongs_to :sender,     :class_name => 'User', :foreign_key => 'from'
    belongs_to :receipent,  :class_name => 'User', :foreign_key => 'user_id'

Now say p1 is sending a message to p2

p1.sent_messages.create(title: "test title", body: "test body", receipent: p2)
#<Message id: 1, title: "test title", body: "test body", user_id: 2, from: 1 ... ... >

Now for a message, you can get both sender and receipent directly like

@messages = Message.includes(:sender, :receipent) # You can load only sender or only receipent

#In View 

Need Your Help

Compile std::regex_iterator with gcc

c++ regex linker g++ c++11

I can create .o file with g++ -c test.cpp -std=c++0x, but cant link it, got next errors:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.