Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages and disadvantages of Ruby on Rails polymorphic relationships [closed]

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

like image 709
Szymon Lipiński Avatar asked Nov 25 '09 18:11

Szymon Lipiński


People also ask

What is polymorphic relation in rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

What is polymorphic Ruby?

Polymorphism is an important concept in object-oriented programming. It allows us to implement many different implementations of the same method, helping with code reusability and avoiding redundancy. In Ruby, we can implement polymorphism using inheritance or duck typing.

What is STI associations in Rails?

In Single-Table Inheritance (STI), many subclasses inherit from one superclass with all the data in the same table in the database. The superclass has a “type” column to determine which subclass an object belongs to. In a polymorphic association, one model “belongs to” several other models using a single association.

What is STI in Ruby?

Single Table Inheritance (STI) models are defined as separate classes inheriting from one base class, but they aren't associated with separate tables — they share one database table. The table contains a type column that defines which subclass an object belongs to.


1 Answers

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.

like image 98
tadman Avatar answered Sep 17 '22 18:09

tadman