Search code examples
ruby-on-railsrubyoopdatabase-designsti

Rails: should I use STI?


I want to present my case, and know whether or not I should use STI solution.
I am creating a message-board website and so far I have couple of Models: User, Topic, Post..
to make it clear: Post is like a comment for a Topic. Topic has title and content. Post has only has content.

Now, the User has the option to Like/Dislike a Post or a Topic. I thought about three options:

  1. Topic and Post don't have a connection (each Model has "num_of_likes", "num_of_dislikes")
  2. Topic inherit Post.
  3. Topic and Post inherit from a Base Model which can be called LikeableObj for example.

Which of those three options is the most suitable for my needs?
Is there a fourth option I didn't think about?
What if I'd like in the future to have a third Model which can be Liked?


Solution

  • I assume you'll want to keep track of whether a user has liked a certain post or topic, so I would make a join model for likes that connects a user to either a post or topic.

    class Like < ActiveRecord::Base
      belongs_to :user
      belongs_to :liked_obj, polymorphic:true, counter_cache:true
    end
    

    Since the liked_obj is polymorphic, it can be a post or a topic. You can then put has_many :likes on those models and a column likes_count, which will be updated automatically as a counter cache.

    If you have any code that deals with likes that is common between Post and Topic, put it in a module Likeable and include it in both classes.