Ruby on Rails最近的活动

col*_*rco 4 ruby-on-rails

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

我有一个包含用户照片的图库,我希望当其他用户对其照片进行评论或投票时会通知他们.

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

ez.*_*ez. 10

简短的回答是:这取决于.如果您只需要最近的活动,并且不需要跟踪活动或完整的"活动源"功能,那么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(e.g. 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, e.g 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
Run Code Online (Sandbox Code Playgroud)

在我们做的answer_controller中

Class AnswersController
    def create
        ...
        Activity.add(current_user, ActivityType::QUESTION_ANSWERED, @answer)
        ...
    end
end
Run Code Online (Sandbox Code Playgroud)

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

@activities = @user.activities
Run Code Online (Sandbox Code Playgroud)

  • 为了避免使用这种活动日志记录污染模型,我建议使用Rails Observers:http://api.rubyonrails.org/classes/ActiveRecord/Observer.html (6认同)