Justin
Justin

Reputation: 1956

Tracking Followers Over Time

I want to build functionality in my Rails application that shows follower trends over time.

Currently, my following methodology involves creating and destroying relationship objects - following creates an object with the IDs of the follower and followed and unfollowing deletes that relationship object.

Since the relationship object is deleted upon an unfollow, it's impossible to go back and look at how many followers existed for a followed at any given time.

To solve this, the best solution I can think of is this:

Instead of deleting a relationship object upon unfollowing, create a new object with a negative value of, say, -1. Following would create an object with a positive value of +1. Therefore, adding up the total values for a given pair would yield whether or not they were currently following (1 or 0), while historical trends could also be calculated by adding up the total following values for a given followed.

My question is: Is this the most elegant solution this problem? Is there an easier way to do it? I realize that it's possible to use cron jobs to output a daily number, but that seems like it would duplicate data. Any other suggestions?

Any help would be greatly appreciated!

Upvotes: 0

Views: 127

Answers (2)

rewritten
rewritten

Reputation: 16435

just use paranoia

https://github.com/radar/paranoia

class Relationship < ActiveRecord::Base
  acts_as_paranoid

  ...
end

(if you have a unique index over the two numeric ID columns, remove it, use a plain index)

Then you can have

def currently_following_count(uid)
  Relationship.where(:followed_id => uid).count
end

def historical_following_count(uid)
  Relationship.unscoped.where(:followed_id => uid).count
end

Upvotes: 1

Timothy Hunkele
Timothy Hunkele

Reputation: 887

I would add an active field then instead of deleting the relationship record I would set the record to inactive. Then you'll have to update all of your user facing queries to reflect active = 1. Then you can use the records with active = 0 for reporting purposes. You can also add a deactivated_at field that stores the date that the record was deactivated.

An example scenario would be user 1 follows user 2, follows user 3, follows user 4, un-follows user 2, re-follows user 2, un-follows user 4.

follower_id followed_id active created_at deactivated_at
1           2           0      9/10/2012  9/13/2012
1           3           1      9/10/2012  NULL
1           4           0      9/10/2012  9/17/2012
1           2           1      9/16/2012  NULL

Upvotes: 1

Related Questions