Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a "feed" from multiple rails models, efficiently?

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.

like image 291
jay Avatar asked Oct 20 '11 20:10

jay


1 Answers

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 ;-)

like image 58
Victor Pudeyev Avatar answered Oct 03 '22 13:10

Victor Pudeyev