Re: Multiple relations between two models

Bala Paranj
Wed, 18 Oct 2006 13:34:40 -0000

On 10/18/06, Stewart
<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:
>
>
> I currently have two models.  These are user and message.
>
> Message belongs to user and user has many messages.  I have set the
> relation up so I can do something like the following...
>
> #code
> current_user.messages
> ##end code
>
> This gets a list of all of the incoming messages for the logged user.
> This works just fine.
>
> What I really want to do, is to be able to say something like...
>
> #code
> message.sender
> ##end code
>
> and have this return a model of the user that sent the message.
What''s
> the best way to achieve this if I already have one relation?  I have a
> field in the user model that is set up to record the user ID of the
> person who sends the message.  I am just not sure how to express the
> relationship in rails using active record.


You can use the dynamic finder:

message.find_sender_by_id( :id => userID )

This is the simplest way to find the sender object.