Ruby-on-rails – Advantages and disadvantages of Ruby on Rails polymorphic relationships

activerecorddatabaserubyruby-on-rails

What advantages and disadvantages do you know of Ruby on Rails polymorphic relationships.

Best Solution

Advantages:

  • You can link anything to anything quite easily
  • Adaptable relationships help accommodating unforeseen circumstances
  • Very easy to implement relationships
  • Great for ad-hoc systems

Disadvantages:

  • Foreign keys not practical
  • Indexes include another dimension of complexity
  • Relationships between tables hard to identify when using STI
  • Database diagramming tools cannot interpret
  • Not always practical for join models
  • Strongly discouraged for systems where data integrity must be verified

I'm a big fan of using relationships of this sort for records that are attached to a large number of things as required, for example, a comment or annotation record which may apply to a wide variety of records.

It is not very well suited for situations where the relationship is exercised in a JOIN frequently. That is, the polymorphic association should not be in the middle of a relationship between records, but as something on the perimeter.