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/Associations/ClassMethods.html#method-i-belongs_to 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 -- Posted via http://www.ruby-forum.com/. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

