Polymorphic association
suggest changeThis 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents