Mendable.com home

Polymorphic Single Table Inheritance (STI)

30 Mar 2010

Migration:

  create_table :addresses do |t|
    ....
    t.references :addressable, :polymorphic => true
    t.string :type
    t.timestamps
  end

Address Models:

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

User Model:

class User < ActiveRecord::Base
  has_many :addresses, :dependent => :destroy
  has_one :invoice_address, :as => :addressable
  has_one :delivery_address, :as => :addressable
end

Order Model:

class Order < ActiveRecord::Base
  has_many :addresses, :dependent => :destroy
  has_one :invoice_address, :as => :addressable
  has_one :delivery_address, :as => :addressable
end

Get Funky:

>> u = User.new
=> <User id: nil ...>
>> u.build_invoice_address
=> #<InvoiceAddress id: nil, addressable_id: nil, addressable_type: "User", 
created_at: nil, updated_at: nil, type: "InvoiceAddress">
>> u.build_delivery_address
=> <DeliveryAddress id: nil, addressable_id: nil, addressable_type: "User", 
created_at: nil, updated_at: nil, type: "DeliveryAddress">
>> o = Order.new
=> #<Order id: nil ...>
>> o.build_invoice_address
=> #<InvoiceAddress id: nil, addressable_id: nil, addressable_type: "Order", 
created_at: nil, updated_at: nil, type: "InvoiceAddress">

Sweet :)