I recently added User activity tracking functionality to my application which tracks user interaction with several models, and several different actions within each model.
class User
has_many :activities, :order => 'created_at desc'
def log_activity(object, type)
activities.create(:subject_type => object.class.name, :subject_id => object.id, :subject_action_type => type)
end
end
Now I call this method after a User creates/updates/deletes various objects and display this activity on the user profile. I imagine that after a while the Activities table will contain so many records it’s going to get to the point where it effects load times. I was wondering what a good implementation would be to manage this in a user-friendly way and keep my database running smoothly.
I was thinking of setting up some kind of scheduled task that cleans up old records after x amount of time. Perhaps you can give some advice as to how to accomplish this or recommend an even better solution?
I’m using PostgreSQL as my database of choice.
Your
activitieslazy loads so it won’t pull in all of the associated activities unless you ask for them. So when you say this:All you’re doing to the database is a single INSERT: there is no
select * from activities where ...to buildactivities, there’s just the INSERT from thecreatecall.So you don’t have anything to worry about from your
log_activitymethod.If you want to limit the size of your
activitiestable then a simple:every now and then should be fine to clear out the dead wood. The
'10 days'is, of course, just for illustration.