如何通过多个其他表检索相关记录?



这里有一个简单的设置,其中用户将始终是患者,并且用户可能是也可能不是医生:

# user.rb
has_one :physician
has_one :patient
# physician.rb
belongs_to :user
validates_uniqueness_of :user_id
has_many :appointments
has_many :patients, :through => :appointments
# patient.rb
belongs_to :user
validates_uniqueness_of :user_id 
has_many :appointments
has_many :physicians, :through => :appointments

这一切都连接到约会和对话,像这样:

# appointment.rb
belongs_to :physician
belongs_to :patient
has_one :conversation
has_many :messages, through: :conversation
# conversation.rb
belongs_to :appointment
belongs_to :sender, foreign_key: :sender_id, class_name: "User"
belongs_to :recipient, foreign_key: :recipient_id, class_name: "User"
has_many :messages

有时候我真的很想这样做:

current_user.conversations

,但这不起作用,我必须这样做:

current_user.physician.appointment.includes(:conversation)
# somehow combine results with this
current_user.patient.appointment.includes(:conversation)

问题我需要做什么(以及在哪里),以便我可以调用current_user.conversations,它将检索所有对话(即作为患者,作为医生的对话(注意用户可能是也可能不是医生)。

注意:如果我的建议不是很好的实践,请接受建议。

根据您目前的设计,在User模型中,您可以简单地为conversations添加一个方法:

def conversations
Conversation.where(sender: self).or(Conversation.where(recipient: self))
end

我不知道为什么一个会话会有一个senderrecipient作为一个用户可以是发送者(消息)和接收者(消息)在一个会话。我会从conversations表中删除sender_idrecipient_id,只匹配基于appointments的对话。

def conversations
Conversation
.joins(appointment: [:physician, :patient])
.where('physicians.user_id = :user_id or patients.user_id = :user_id', user_id: id)
end

最新更新