我正在创建一个消息传递系统。用户可以通过向多个收件人发送消息来开始对话,而这些收件人又可以回复。
我想找到用户参与的所有对话。即。他们在对话中创作了一条消息或者是消息的收件人的对话。
目前我的模型是这样的
# 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 上创建一个范围来实现这样的目标
Conversation.involving(user)
不确定如何为此编写作用域/sql。感觉我需要一个相当于 OR 语句的地方。
即。在伪代码中
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])
这是在 user_id 外键上执行 where 子句,这样您就不必弄清楚 ActiveRecord 将分配给用户表的表别名(因为它会被连接两次)。
关于sql - 查询以查找用户参与的所有消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998622/