Recent Activities in Ruby on Rails

What is the best way to implement a StackOverflow-style latest events page?

I have a Gallery with photos of users, and I want them to be notified when other users comment on or vote for their photos.

Should I create a new table that contains the latest actions (updated whenever the user sends a comment or votes), or should I just use the MySQL query?

+4
source share
2 answers

Short answer: it depends. If you need only the most recent actions and don’t need to track the actions or the full activity feed function, SQL is the way to go. but if you see the need to do full activity, you can create a model for it.

We recently made a stream of activity in our project. This is how we modeled it

Class Activity belongs_to :user_activities # all the people that cares about the activity belongs_to :actor, class_name='user' # the actor that cause the activity belongs_to :target, :polymorphic => true # the activity target(eg if you vote an answer, the target can be the answer ) belongs_to :subtarget, :polymorphic => true # the we added this later since we feel the need for a secondary target, eg if you rate an answer, target is your answer, secondary target is your rating. def self.add(actor, activity_type, target, subtarget = nil) activity = Activity.new(:actor => actor, :activity_type => activity_type, :target => target, :subtarget => subtarget) activity.save! activity end end 

in answer_controller we do

 Class AnswersController def create ... Activity.add(current_user, ActivityType::QUESTION_ANSWERED, @answer) ... end end 

To get a list of recent actions from the user, we do

 @activities = @user.activities 
+10
source

This was written into a great article that shows the full use of AR, observers, and the migration you need.

http://mickeyben.com/blog/2010/05/23/creating-an-activity-feed-with-rails/

Observers save you by cluttering your models with this information, as well as adding actions that you can send by email or something else that you need to do.

+2
source

All Articles