
The Likes Table Problem: Why We Went Polymorphic.
A few days ago, I was working on adding a Community section to an application. The idea was simple, users should be able to: Create posts Leave comments Like posts Like comments We also had a separate News section. The new requirement was users should be able to like news articles as well. Building model for posts and comments was pretty straight forward. The real challenge was to model the likes table. The Problem: How Do We Store Likes? We’re using PostgreSQL, so enforcing relationships with foreign keys is easy and clean. If only one thing could be liked (say, News), the schema would be simple, we would have a news_like table which could look something like this: user_id news_id timestamp (foreign key) (foreign key) But we didn’t have one entity. We had three. posts , comments and news . We had to decide: Do we create three separate like tables? Or do we design one flexible solution? Option 1: Three Separate Tables We could create three tables: post_likes , comment_likes and news_li
Continue reading on Dev.to
Opens in a new tab



