ActiveRecord associations and more Part 2

Polymorphic Associations

Ruby on Rails Guide states “with polymorphic associations, a model can belong to more than one other model, on a single association”. The definition indicates that this type of polymorphic association has the potential to make our code DRY.

has_many :through or has_and_belongs_to_many ?

Previously we saw that has_and_belongs_to_many association removes the need of a join model between two connecting models and only has a join table.

has_and_belongs_to_many association
has_many :through association
  • The first thing that comes to my mind is that the case when Manifest model has to have some data for example name or description field. In this case, we can never validate this data in has_and_belongs_to_many association since there is no model of Manifest. The following model can be used in has_many :through association
Manifest model can have validations
  • The advantage of having a separate model is that you can add additional methods to your existing model and use it as a shared functionality in your codebase.
  • Another difference we can mention is the creation of model instances. With has_many :through we can create a Part model instance with the following way
  • has_and_belongs_to_many association is much more suitable when you are working with an already built database. Creating an additional model when you try to implement has_many :through association might break some parts of the system.


Official Ruby on Rails guide really gives good advice on this issue,



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ali Erbay

Ali Erbay


Full Stack Developer BDD/TDD || Ruby on Rails || React || React Native || NodeJS || Express