VocabReminder
Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

Simple Activity Stream Implementation in Rails

       

There are many ways to tackle the Facebook style activity stream feature for your app. The simplest approach, which you can tack on at almost any moment, is what I'll describe here. You don't have to create a new model for news feed items or create any polymorphic associations. You simply query for the records on separate models you would like aggregated in the stream, and render a partial for that record, which Rails will map for you.


# in app/controllers/home_controller.rb
def index
 @activity_stream = (Forum.find(:all, :limit => 10, :conditions=>["created_at > ?", 1.day.ago]) + ForumPost.find(:all, :limit => 10)).sort_by {|item| - item.created_at.to_i}
end  

The sort_by method at the end places all of your feed item into descending chronological order. Omit the minus sign and they will be sorted in ascending order.


sort_by {|item| - item.created_at.to_i} # in descending chronological order

Show your latest activity in your views...

app/views/home/index.html.erb

<%= render @activity_stream rescue nil %>

This assumes that you will have created the partials for each resource using Rails conventions i.e., you have in created the partials for the models like so app/views/_[the model name].html.erb. In this instance, you should have app/views/forums/_forum.html.erb and app/views/forum_posts/_forum_post.html.erb

You can rename the partials to something like stream_forum.html.erb, if you already have the forum partial gainfully employed. You'll need to change the view and prob. throw it into a loop to either check for a condition or use _stream[model name].html.erb as the convention for any stream items.

Tagged w/ #activtiy stream #facebook #newsfeed #polymorphic associations #simpleruby on rails