Sql 查询以查找用户正在参与的所有邮件
我正在创建一个消息传递系统。用户可以通过向多个收件人发送消息来启动对话,而这些收件人又可以回复 我想查找用户正在参与的所有对话。也就是说,他们在对话中编写了一条消息或是一条消息的接收者 目前我的模型是这样的Sql 查询以查找用户正在参与的所有邮件,sql,ruby-on-rails,Sql,Ruby On Rails,我正在创建一个消息传递系统。用户可以通过向多个收件人发送消息来启动对话,而这些收件人又可以回复 我想查找用户正在参与的所有对话。也就是说,他们在对话中编写了一条消息或是一条消息的接收者 目前我的模型是这样的 # Message belongs_to :conversation belongs_to:user #author has_many :receipts has_many :recipients, :through => :receipts # Conversation has_m
# Message
belongs_to :conversation
belongs_to:user #author
has_many :receipts
has_many :recipients, :through => :receipts
# Conversation
has_many :messages
# User
has_many :receipts
has_many :incoming_messages, through: :receipts, :class => 'Message'
# Receipt
belongs_to :message
belongs_to :user
Conversation.involving(user)
我想在对话中创建一个范围来实现这样的目标
# Message
belongs_to :conversation
belongs_to:user #author
has_many :receipts
has_many :recipients, :through => :receipts
# Conversation
has_many :messages
# User
has_many :receipts
has_many :incoming_messages, through: :receipts, :class => 'Message'
# Receipt
belongs_to :message
belongs_to :user
Conversation.involving(user)
不确定如何为此编写scope/sql。我觉得我需要一个相当于或陈述的东西
例如,在伪代码中
conversations where (messages.recipient_ids include user.id OR messages.user_id == user.id)
我假设我对系统的建模是正确的。如果没有更好的方案建议,也将不胜感激
任何人都能帮上忙。类似的方法应该可以:
Conversation.includes(messages: :receipts).where(["messages.user_id = :user_id OR receipts.user_id = :user_id", user_id: user.id])
这是在用户id外键上执行where子句,这样您就不必计算ActiveRecord将分配给用户表的表别名(因为它将被连接两次)。太好了,我可以问一下为什么选择includes而不是join吗?通常是习惯。如果视图不需要这些表中的任何数据,那么使用联接应该更快。