Rails3 ActiveRecord associations

I have Messages and User models with corresponding tables.
The Messages table has such fields like user_from and user_to.

How can associate the models to be able to access sender and recipient
users objects:

message.user_from.name
message.user_to.id

Thanks.

slava wrote in post #1064971:

I have Messages and User models with corresponding tables.
The Messages table has such fields like user_from and user_to.

I hope you mean your model names are “Message” and “User”. Model names
should always be singular form. The underlying tables will be plural
form.

How can associate the models to be able to access sender and recipient
users objects:

message.user_from.name
message.user_to.id

You will need two foreign keys. You won’t be able to rely solely on the
Rails naming conventions. Thankfully, the Rails defaults can be easily
overridden.

See:

Pay special attention to the options :class_name and :foreign_key. That
is how you override the Rails defaults and tell the model how to make
the associations.

Example:

User

has_many :sent_messages, :class_name => “Message”, :foreign_key =>
“sender_id”
has_many :received_messages, :class_name => “Message”, :foreign_key =>
“recipient_id”

Message

belongs_to :sender, :class_name => “User”, :foreign_key => “sender_id”
belongs_to :recipient, :class_name => “User”, :foreign_key =>
“recipient_id”

Then you would have:
message.sender
message.recipient