Search code examples
ruby-on-railsdatabase-designmodelsocial-networkingdatabase-normalization

"Following" and "favorites" relationship models in Rails---one master model or specific models for each relationship


I'm working on an app where a user can have one of two kinds of relationships to other users---either favoriting them, or following them---and I suppose the reverse actions, is favorited by and is being follow by will also come up as methods I'll want to call.

What are the considerations I should have in making my user model? Specifically, should I have one model, relationships, that specifies:

Relationships
user_1 | relationship_type | user_2

where relationship_type is favoriting or following?

Or should I have 2 separate models:

Favorites
user_1 | user_2

Follows
user_1 | user_2

I don't know a whole lot about databases, so can I ask what are the considerations in choosing between these two potential setups? Is 2 more normalized than 3, or less? Does that matter? Under what circumstances?

UPDATE

Sorry this just struck me: let's say there's a third relationship, like "reviews"/"reviewed_by"--and the question is about 3, rather than 2 different bidirectional relationship types. Does increasing the number of relationship types impact this?

Favorites
user_1 | user_2

Follows
user_1 | user_2

Reviews
user_1 | user_2

Solution

  • I would go for 2 different models in one table, that is, use the Single Table Inheritance Pattern. This way, you get a db table that looks close to your option #1 and have a clean model with two different classes for Favourites and Follows on the Object Model side resulting in clearer code & naming.

    As for Naming, Michael Hartl uses "followers" and "followed_users" in his example, which seems quite similar to what you are striving at: http://ruby.railstutorial.org/chapters/following-users#top