简体   繁体   English

带有Rails ActiveRecord的SQL UNION

[英]SQL UNION with Rails ActiveRecord

I have two models in my app, notes and highlights. 我的应用程序中有两个模型,注释和亮点。 They are defined like: 它们的定义如下:

class Note < ActiveRecord::Base
  belongs_to :user
end

class Highlight < ActiveRecord::Base
  has_and_belongs_to_many :users
end

Now, I want both accessible in the same stream, sorted by creation date. 现在,我想在同一个流中访问它们,按创建日期排序。 I couldn't wrap my head around how to do this in ActiveRecord, so I put together this query: 我无法解决如何在ActiveRecord中执行此操作,因此我将此查询放在一起:

SELECT book_id, page, content, created_at FROM `highlights` 
INNER JOIN `highlights_users` ON `highlights`.id = `highlights_users`.highlight_id 
WHERE (`highlights_users`.user_id = 1 ) 
UNION SELECT book_id, page, content, created_at FROM notes 
ORDER BY created_at DESC

Add of course, it works, but doesn't feel very Rails-y. 添加当然,它的工作原理,但感觉不太Rails-y。 Plus, I don't know how to tell which items are notes and which are highlights. 另外,我不知道如何判断哪些项目是注释,哪些项目是重点。 The other option is to get the note stream and highlight streams separately, then merge the arrays. 另一种选择是分别获取音符流和高亮显示流,然后合并数组。 That also seems clumsy, and I feel like there must an abstraction somewhere for what I'm trying to do. 这看起来也很笨拙,我觉得在某些地方必须有一个抽象的东西。

Is there some key ActiveRecord functionality I'm missing here? 我在这里缺少一些关键的ActiveRecord功能吗? What's the most efficient way to go about this? 什么是最有效的方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM