在rails / active record上使用ruby进行棘手的联合查询

时间:2014-06-25 18:09:57

标签: ruby-on-rails ruby ruby-on-rails-4 mailboxer

我有

a = Profile.last
a.mailbox.inbox
a.mailbox.sentbox
active_conversations = [IDS OF ACTIVE CONVERSATIONS]

a.mailbox.inbox & active_conversations 

返回我需要的部分内容

我想要

(a.mailbox.inbox& active_conversations)和a.mailbox.sentbox

但我需要它作为SQL,以便我可以有效地订购它。我想通过(' updated_at')

订购

我尝试过加入和其他事情,但他们没有工作。 (a.mailbox.inboxa和sendbox的类是

ActiveRecord::Relation::ActiveRecord_Relation_Conversation

但是

(a.mailbox.inbox & active_conversations)

是一个数组

修改

像a.mailbox.inbox这样简单的东西加入一些a.mailbox.sentbox我应该可以使用,但我似乎也无法弄明白。

1 个答案:

答案 0 :(得分:1)

而不是做

(a.mailbox.inbox & active_conversations)

你应该可以做到

a.mailbox.inbux.where('conversations.id IN (?)', active_conversations)

我认为Conversation类(及其基础conversations表)应该根据邮箱代码正确。

但是,这会为您提供ActiveRelation对象而不是数组。您可以使用to_sql将其转换为纯SQL。所以我认为这样的事情应该有效:

# get the SQL of both statements
inbox_sql = a.mailbox.inbux.where('conversations.id IN (?)', active_conversations).to_sql
sentbox_sql = a.mailbox.sentbox.to_sql

# use both statements in a UNION SQL statement issued on the Conversation class
Conversation.from("#{inbox_sql} UNION #{sentbox_sql} ORDER BY id AS conversations")