I have two models Purchase and Address. I\'m trying to make Address polymorphic so I can reuse it in my Purchase model fo
I think you've misunderstood what polymorphic associations are for. They allow it to belong to more than one model, Address here is always going to belong to Purchase.
What you've done allows an Address to belong to say, Basket or Purchase. The addressable_type is always going to be Purchase. It won't be ShippingAddress or BillingAddress which I think you think it will be.
p.build_shipping_address doesn't work because there isn't a shipping address model.
Add class_name: 'Address' and it will let you do it. However it still won't work the way you expect.
I think what you actually want is single table inheritance. Just having a type column on address
class Purchase < ActiveRecord::Base
has_one :shipping_address
has_one :billing_address
end
class Address < ActiveRecord::Base
belongs_to :purchase
...
end
class ShippingAddress < Address
end
class BillingAddress < Address
end
This should be fine because shipping and billing address will have the same data, if you've got lots of columns that are only in one or the other it's not the way to go.
Another implementation would be to have shipping_address_id and billing_address_id on the Purchase model.
class Purchase < ActiveRecord::Base
belongs_to :shipping_address, class_name: 'Address'
belongs_to :billing_address, class_name: 'Address'
end
The belongs_to :shipping_address will tell rails to look for shipping_address_id with the class name telling it to look in the addresses table.