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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With