P
P
Pavel Shcheglov2016-03-15 18:00:50
Ruby on Rails
Pavel Shcheglov, 2016-03-15 18:00:50

How to make the right association for likes?

Hello.
I am making a rating system on the site and the urgent question arose of how to properly implement it.
Given:
User can like a comment, post, etc.
How models look like,

User
has_many :likes
has_many :comments, through: :likes

Like
belongs_to :user
belongs_to :comment

Comment
has_many :likes

And everything works fine, but there is one "but". If you start to expand the functionality of likes, for example, make it possible to lap up posts, then the likes record will look something like this:
Likes.new(comment_id: nil, post_id: 1, user_id: 1)
The problem is that if you like a post, a record with an empty comment_id field will be created, if you like a comment, a record without post_id is created. I don't feel sorry for it, let it be created, but something internally protests against such a mess :)
Here's how to avoid creating empty records in the table? What is the best solution to such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2016-03-15
@hrumhrumble

You need Polymorphic Associations

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question