如何在这两个轨道模型之间建立关系



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

这是对的吗?

您必须重命名关联以区分它们:

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

相关内容

  • 没有找到相关文章

最新更新