与收件人的邮件的关联设置

时间:2018-02-04 17:06:00

标签: ruby-on-rails

我很想知道建立模型和协会的最佳方式是我想要实现的目标。

用户可以创建消息。该邮件可以包含一个或多个用户的收件人。

如何设置关联以便我可以查看用户发出的消息,还可以查看收件人是用户ID的消息?我是做连接模型还是做:

用户has_many消息,消息包含多个收件人(存储message_id和user_id),如果这是最好的方式,我如何访问用户不是邮件所有者而是收件人的邮件?

1 个答案:

答案 0 :(得分:1)

class User << ApplicationRecord
  has_many :sent_messages, class_name: "Message"
  has_many :recipients
  has_many :received_messages, :through => :recipients, :source => :message
end

class Message << ApplicationRecord
  belongs_to :sender, class_name: "User"
  has_many :recipients
  has_many :receivers, through: :recipients
end

class Recipients<< ApplicationRecord
  belongs_to :message
  belongs_to :receiver, class_name: "User"
end

然后你可以:

user = User.find(1)     # First user
user.sent_messages      # Messages sent by user
user.received_messages  # Messages received by user