2

我有 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

那是对的吗?

4

1 回答 1

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
于 2012-04-27T11:42:44.587 回答