2009-08-14 9 views
4

StackOverflowスタイルの最近のアクティビティのページを実装する最良の方法は何ですか?Ruby on Railsの最近の活動

私はユーザーの写真付きのギャラリーを持っており、他のユーザーがコメントしたり、投票したりする際にお知らせします。

最近のアクティビティ(ユーザーがコメントや投稿を投稿するたびに更新される)を含む新しいテーブルを作成するか、単純にMySQLクエリを使用する必要がありますか?

答えて

10

短い答えは次のとおりです。最新のアクティビティだけが必要で、アクティビティや完全な「アクティビティフィード」機能を追跡する必要がない場合は、SQLを使用する方法があります。しかし、完全な活動フィードの種類のことを行う必要がある場合は、モデルを作成することができます。

最近私たちのプロジェクトではアクティビティストリームを作成しました。ここでは、我々はそれを我々はこれがにまで書き込まれてい

@activities = @user.activities 
+1

合意。最初はSQLクエリを使い始めましたが、それが複雑すぎたり、パフォーマンスが悪かったり、ニーズに合っていないような場合は、アクティビティモデルを作成してください。 – ryanb

+6

この種のアクティビティロギングでモデルを汚染しないようにするには、Rails Observersをお勧めします: http://api.rubyonrails.org/classes/ActiveRecord/Observer.html – bloudermilk

2

を行うユーザーからの最近の活動のリストを取得するには

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

を行うanswer_controllerで

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 

をモデル化する方法でありますAR、Observersの完全な使用を示し、必要な移行を提供する素晴らしい記事です。

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

Observersあなたはこの情報を使用してモデルを混乱ようにだけでなく、あなたが電子メールを送ることができるか、他何でもあなたがする必要がある活動を追加し、保存します。

+0

リンクが機能しません –

+1

右リンク:http:// mickeyben .com/blog/2010/05/23/creating-an-activity-feed-with-rails / –