Polymorphic association

suggest change

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

addresses needs addressable_id and addressable_type. The type column stores "Human" or "Company".

Without the polymorphic association, addresses would have a foreign key for every parent, and only one of those keys would be set. An address in this example belongs to either a human or a company:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents