【问题标题】:Query to find all messages a user is participating in查询以查找用户参与的所有消息
【发布时间】:2014-07-29 01:14:45
【问题描述】:

我正在创建一个消息传递系统。用户可以通过向多个收件人发送消息来开始对话,而这些收件人又可以回复。

我想查找用户参与的所有对话。即。他们在其中创建了消息或在会话中是消息的接收者的会话。

目前我的模型是这样的

# 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)

我假设我正确地建模了系统。如果没有更好的架构建议,我们将不胜感激。

任何人都可以帮忙。

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    这样的事情应该可以工作:

    Conversation.includes(messages: :receipts).where(["messages.user_id = :user_id OR receipts.user_id = :user_id", user_id: user.id])
    

    这是在 user_id 外键上执行 where 子句,这样您就不必弄清楚 ActiveRecord 将分配给 users 表的表别名(因为它会被连接两次)。

    【讨论】:

    • 太好了,请问您为什么选择包含而不是加入?
    • 习惯,主要是。如果您的视图不需要这些表中的任何数据,则使用联接应该更快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多