I have two models in my application, notes and highlights. They are defined as follows:
class Note < ActiveRecord::Base
belongs_to :user
end
class Highlight < ActiveRecord::Base
has_and_belongs_to_many :users
end
Now I want both available in the same thread, sorted by creation date. I could not 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, works, but not really Rails-y. In addition, I do not know how to determine which elements are notes and which are basic. Another option is to get the note stream and select the threads separately, and then combine the arrays. It also seems awkward, and I feel that somewhere there is an abstraction for what I'm trying to do.
Is there any key ActiveRecord functionality that I'm missing here? What is the most effective way to do this?