This is a follow up to Creating “feeds” from multiple, different Rails models. In this question, tadman suggests this method of creating a user feed of recent items from three models (Ticket, Post, Report):
@items = [ Ticket, Post, Report ].inject([ ]) do |a, with_class| a + with_class.find(:all, :limit => 10, :order => 'created_at DESC') end.sort_by(&:created_at).reverse[0, 10]
He suggests this as a method that will work, but that won’t necessarily be the most efficient. He suggests as well than an alternative method would be to “create an index table that’s got a polymorphic association with the various records.”
I’m really interested in learning more about this alternative solution, it seems both more efficient and more elegant. Can anyone tell me how one would do this? Let’s use the same background info from the last question as a base.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
What I did once was, have a separate model Feed (feeds_controller) and update it in after_save callbacks to all the interesting
models. So for example if you have a model Article, have an after_save callback:
def after_save feed = Feed.new feed[:model_name] = 'Article' feed[:item_id] = id feed.save end
then, you can access the feed linearly just like any other model. The computational expense is incurred when saving the the feed, not reading from the feed.
Oh, you can also have Feed has_many :article; has_many :user, has_many :status
and so forth, and then :include
all those resources in the feed, and render them in views. Hope this makes sense 😉
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0