Recent Activities in Ruby on Rails

后端 未结 2 1182
傲寒
傲寒 2021-01-31 23:46

What is the best way to implement a StackOverflow-style Recent Activities page?

I have a Gallery with user\'s photos and I want them to be notified when other

相关标签:
2条回答
  • 2021-02-01 00:38

    This has been written up into a great article which shows the full use of AR, Observers and gives the migration you will need.

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

    Observers save you cluttering your models with this information so as well as adding activities you can send emails or whatever else you need to do.

    0 讨论(0)
  • 2021-02-01 00:43

    The short answer is : it depends. If you only need most recent activities and don't need to keep track of activities, or a full 'activity feed' feature, SQL is the way to go. but if you see the need to do a full activity feed kind thing, You can create a model for it.

    We did a activity stream recently on our project. Here 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(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
    

    in the answer_controller we do

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

    To get a recent activity list from a user we do

    @activities = @user.activities
    
    0 讨论(0)
提交回复
热议问题