Search code examples
ruby-on-railsassociationsmodelshas-one

How to define a 'has_one style' association with one of a multiple different models?


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?


Solution

  • 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.