Forum: Ruby on Rails Rails3 ActiveRecord associations

Posted by slava (Guest)
on 2012-06-18 14:59
(Received via mailing list)
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.
Posted by Robert Walker (robert4723)
on 2012-06-18 23:36
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:
http://api.rubyonrails.org/classes/ActiveRecord/As...

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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.