I want to create an activity feed from recent article and comments in my rails app. They are two different types of activerecord (their table structures are different).
Ideally I would be able to create a mixed array of articles and comments and then show them in reverse chronological order.
So, I can figure out how to get an array of both articles and comments and then merge them together and sort by created_at, but I’m pretty sure that won’t work as soon as I start using pagination as well.
Is there any way to create a scope like thing that will create a mixed array?
One of the other problems for me, is that it could be all articles and it could be all comments or some combination in between. So I can’t just say I’ll take the 15 last articles and the 15 last comments.
Any ideas on how to solve this?
When I’ve done this before I’ve managed it by having a denormalised
UserActivitymodel or similar with abelongs_topolymorphic association to anActivitySource– which can be any of the types of content that you want to display (posts, comments, up votes, likes, whatever…).Then when any of the entities to be displayed are created, you have an
Observerthat fires and creates a row in theUserActivitytable with a link to the record.Then to display the list, you just query on
UserActivityordering bycreated_atdescending, and then navigate through the polymorphicactivity_sourceassociation to get the content data. You’ll then need some smarts in your view templates to render comments and posts and whatever else differently though.E.g. something like…
user_activity.rb:
comment.rb (post/whatever)
activity_source_observer.rb