问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/1988915/multipe-relationships-in-rails-where-the-class-name-does-not-match-the-associati