Ruby on Rails最近的活动

实现StackOverflow样式的Recent Activities页面的最佳方法是什么?

我有一个包含用户照片的图库,我希望在其他用户评论或投票时通知他们。

我应该创建一个包含最近活动的新表(每当用户发表评论或投票时更新)或者我应该只使用MySQL查询吗?

简短的回答是:这取决于。 如果您只需要最近的活动,并且不需要跟踪活动或完整的“活动源”function,那么SQL就是您的选择。 但是如果你看到需要做一个完整的活动饲料类的东西,你可以为它创建一个模型。

我们最近在项目上做了一个活动流。 这是我们如何建模它

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 

在我们做的answer_controller中

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

要从我们这样做的用户处获取最近的活动列表

 @activities = @user.activities 

这已被写入一篇很棒的文章,该文章展示了AR,Observers的全面使用,并提供了您需要的迁移。

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

观察者可以使用这些信息来保护您的模型混乱,以及添加您可以发送电子邮件或其他任何您需要做的活动。