我有2个模型:User
和PrivateMessage
必须关联(因为用户有许多私人消息作为接收者和发件人,私人消息属于用户)
这是我的private_messages
表结构:
private_messages:
sender_id:integer
reciever_id:integer
title:string
message:text
我很难理解如何为发件人用户和收件人用户连接相同的邮件,现在我的模型代码如下:
class User < ActiveRecord:Base
has_many :private_messages
end
和
class PrivateMessage < ActiveRecord::Base
belongs_to :user, :through => :sender_id
belongs_to :user, :through => :reciever_id
end
这是对的吗?
答案 0 :(得分:6)
您必须重命名您的关联以区分它们:
class PrivateMessage < ActiveRecord::Base
belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id'
end
class User < ActiveRecord::Base
has_many :sent_messages, :class_name => 'PrivateMessage', :foreign_key => 'sender_id', :dependent => :destroy
has_many :received_messages, :class_name => 'PrivateMessage', :foreign_key => 'receiver_id', :dependent => :destroy
end