如何建立这两种轨道模型之间的关系

时间:2012-04-27 11:35:38

标签: ruby-on-rails ruby associations models database-relations

我有2个模型:UserPrivateMessage必须关联(因为用户有许多私人消息作为接收者和发件人,私人消息属于用户)

这是我的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

这是对的吗?

1 个答案:

答案 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