Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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. 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? What's the most efficient way to go about this?

like image 202
Jack Hoge Avatar asked Nov 05 '22 04:11

Jack Hoge


1 Answers

Single table inheritance is likely the abstraction that you are looking for.

http://ar.rubyonrails.org/classes/ActiveRecord/Base.html

http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html

http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html

like image 143
jdl Avatar answered Nov 09 '22 04:11

jdl