Reputation: 4391
I have a private message model that relates to two users, how do I setup an association so that PM.sender is the sender's user model and PM.receiver is recipient's user model? (so that I can call PM.sender.username etc.)
I have a sender_id and receiver_id field.
Upvotes: 0
Views: 886
Reputation: 66293
Assuming model classes Message
and User
, in your Message
model:
class Message < ActiveRecord::Base
belongs_to :sender, :class_name => 'User'
belongs_to :receiver, :class_name => 'User'
end
Because the class name can't be deduced from the association name the explicit :class_name
is required.
Update: Having just checked, the :foreign_key
parameter shouldn't be required as long as the name of the foreign key is the name of the association followed by _id
, which it is in this case.
Upvotes: 5