I am trying to fuse to objects into a single stream.
I created a new model and controller called Newsfeed. I have it so that newsfeed has_many :messages and has_many
I'm sure this can be streamlined from it's ghetto-polymorphism, but it works for me, and I had an identical struggle with the "how do I combine all these model results?!"
I use a separate model, like you, and an observer:
class NewsfeedObserver < ActiveRecord::Observer
observe Message, Image
def after_save(object)
@item = Newsfeed.create(
:item_id => object.id,
:item_type => object.class.to_s
)
end
end
Then in the Newsfeed model you can pull and collate as you like:
def self.get_items
item_list = []
items = find(:all, :order => "created_at DESC", :limit => 30)
items.collect{ |i| i.item_type.constantize.find(i.item_id) }
end
Then just pull them and display in your view however you like.
#Controller
def index
@feed = Newsfeed.get_items
end
Moving forward I will probably start to pack more into the stream-tracking model in order to save hits on the other tables, but hopefully you get the idea.