Polymorphic associations for comments or no?

16 views
Skip to first unread message

Johnny Stewart

unread,
May 16, 2016, 8:52:09 AM5/16/16
to rubyonra...@googlegroups.com
When looking at comments which will be made on different types (say
post, picture, article) I see a lot of advice towards using polymorphic
associations for this. Ryan Bates has a good railscast on it:

http://railscasts.com/episodes/154-polymorphic-association-revised

However, I'm not sure I see why this is such a good idea in this case.
Would it not make more sense to have multiple comment types:

PostComment < Comment
PictureComment < Comment

etc.

Now we have the same amount of comment rows and we maintain referential
integrity, although we do now have more tables..

Can someone point me in the direction of why polymorphic associations
are the way to go rather than using inheritance and multiple tables in
the db? Does it make much difference?

--
Posted via http://www.ruby-forum.com/.

Greg Navis

unread,
May 24, 2016, 7:06:39 AM5/24/16
to rubyonra...@googlegroups.com
I think it depends on your use case. Things to consider:

1. Selecting all comments of a user via 1 association or N associations (and 1 vs N queries).
2. Storing more data in the table (:commentable_type).
3. Maintaining and testing one model vs testing N models.

I think the biggest problem with separate comment models is that references from other models are the fact that you need N times more associations to reference a comment (e.g. user.post_comments, user.picture_comments, ... instead of user.comments).
Reply all
Reply to author
Forward
0 new messages