Has_many :through question

I’m working on a simple messaging service where a user can send a
message to another user. It’s not email, each user can see their
messages when they login to the site. Now I’m trying to figure out how
to set up a has_many : through with two sets. One set is the sender
having many messages and the other set is all the receiver’s messages.
Also with two sets I can’t use the normal attribute names like
message_id. I need to distinguish between sending and receiving ids. Any
suggestions?

-Anthony

On 4/29/07, Anthony W. [email protected] wrote:

-Anthony
This isn’t has_many :through, it’s just a simple has_many association.

class User
has_many :sent_messages, :class_name => ‘Message’, :foreign_key =>
‘sender_id’
has_many :received_messages, :class_name => ‘Message’, :foreign_key
=> ‘receiver_id’
end

class Message
belongs_to :sender, :class_name => ‘User’
belongs_to :receiver, :class_name => ‘User’
end


Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com

##Controller
def email
@user = User.find(params[:id])
user_ids = @user.received_messages.collect {|message|
message.sender_id}
@user_names = user_ids.collect {|uzer| User.find(uzer).fname}
end

##View
<% @user.received_messages.each_with_index do |rec_message, index| %>
From: <%= @user_names[index] %>
Message: <%= rec_message.message %>
<% end %>

Thanks Rick for the suggestion. With your suggestion I’m able to do a
basic messaging system. However, I have to look up all the usernames in
the controller and save them to be displayed in the view to be used the
‘From’ portions of the message. I’d rather not have to do it this way.
I’d be better to pull the name when needed. Is there a way so that I
could do the following.

From: <%= rec_message.from.username %>

-Anthony

Rick O. wrote:

On 4/29/07, Anthony W. [email protected] wrote:

-Anthony
This isn’t has_many :through, it’s just a simple has_many association.

class User
has_many :sent_messages, :class_name => ‘Message’, :foreign_key =>
‘sender_id’
has_many :received_messages, :class_name => ‘Message’, :foreign_key
=> ‘receiver_id’
end

class Message
belongs_to :sender, :class_name => ‘User’
belongs_to :receiver, :class_name => ‘User’
end


Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs