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:
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?
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.