Are polymorphic associations necessary?

I am new to rails trying to understand the advantage of using polymorphic association over multiple belongs_to declarations with corresponding foreign keys. In the railscast of Ryan Bates ( http://railscasts.com/episodes/154-polymorphic-association-revised ), for example, articles, events and photos can have many comments, so he establishes a polymorphic connection using comments.

Why not just add comments to each of the three other assets and include in your table external_files article_id, event_id and photo_id, where only one will be non-zero?

+4
source share
1 answer

You can do it, but there will be flaws. Some I can think of:

  • Local table with many zeros

  • No problem sharing. Comments should change whenever you add a noteworthy model.

  • Rails already supports polymorphic associations and simplifies their use. So why not?

+6
source

All Articles