Ruby on Rails ActiveRecord Associations Polymorphic association

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

This type of association allows an ActiveRecord model to belong to more than one kind of model record. Common example:

class Human < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Company < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

Without this association, you’d have all these foreign keys in your Address table but you only would ever have a value for one of them because an address, in this scenario, can only belong to one entity (Human or Company). Here is what it would look like:

class Address < ActiveRecord::Base
  belongs_to :human
  belongs_to :company
end


Got any Ruby on Rails Question?