Created
April 2, 2011 20:29
-
-
Save dmitryame/899851 to your computer and use it in GitHub Desktop.
followers association with mongoid twitter style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
What is the best way to model user/follower (twitter style) relationships with mongo? Most prominent solution is to embed an array of followers ids in every user object. I'm an idealist, and believe that if we are modeling twitter, we eventually will run into a situation when a user has millions of followers which will blow. The relational many_to_many is not easy to model with mongo, mongo_id tries to offer some implementation of basic associations, but the many_no_many, or has_many through is not there yet and I doubt it ever will be. | |
My solution is a compromise between relational normalization and "embed everything in one document". | |
class User | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
# user will have many followerships, each will embedd a follower user, | |
# the user_id is stored on the followership object | |
references_many :followerships | |
end | |
class Followership | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
# the user_id is stored on this object, which defines the parent user object which is being followed | |
referenced_in :user | |
# embedded user object is a follower | |
embeds_one :follower, :class_name=>"User" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not really, it was all theoretical, and it was never really put in prod.