Reputation: 144
Is there any way to define a has_one style association between models where the association can be with an instance of one of two different models? In particular, I have the following models:
Post
Comment
A user makes a post, and other users can comment on it. But users can also comment on other comments (a la Facebook threads). I'm trying to reflect this relationship in my project by saying that a Comment can have a Target (and that Target can either be a Post or another Comment).
I thought that this would best be done with a has_one association, but as far as I can find, has_one associations can only be used to associate one model with a single other model.
How can I implement a has_many (or another similarly formatted) relationship between these models?
Upvotes: 0
Views: 167
Reputation: 4920
You are in luck as Rails has handled this a long time ago. This is a classic example of polymorphic associations. You need to define your models like this:
class Post
has_many :comments, as: :commentable
end
class Comment
# fields :commentable_type, type: String
# fields :commentable_id, type: Integer
belongs_to :user
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable
end
and you will be able to call comments
on both, as:
post.comments
# And
post.comments.first.comments
Upvotes: 0
Reputation: 4420
You want a polymorphic belongs_to
relationship. belongs_to
goes on the side that's referring to something else (has the xx_id
column), which the Comment model is doing; consider that Post will has_many
Comments, and the opposite of has_many
is belongs_to
. Polymorphic = can refer to any model.
Upvotes: 0