Ruby on Rails ActiveRecord Associations Polymorphic association


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