I have two models Purchase
and Address
. I'm trying to make Address
polymorphic so I can reuse it in my Purchase
model for has_one :billing_address
and has_one :shipping_address
. Here's my schema:
create_table "addresses", force: true do |t|
t.string "first_name"
t.string "last_name"
t.string "street_address"
t.string "street_address2"
t.string "zip_code"
t.string "phone_number"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "state_id"
t.string "city"
t.string "addressable_type" #<--
t.integer "addressable_id" #<--
end
address model:
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
...
end
purchase model:
class Purchase < ActiveRecord::Base
has_one :shipping_address, as: :addressable
has_one :billing_address, as: :addressable
...
end
Everything looks fine to me, but my Rspec tests fail:
Failures:
1) Purchase should have one shipping_address
Failure/Error: it { should have_one(:shipping_address) }
Expected Purchase to have a has_one association called shipping_address (ShippingAddress does not exist)
# ./spec/models/purchase_spec.rb:22:in `block (2 levels) in <top (required)>'
2) Purchase should have one billing_address
Failure/Error: it { should have_one(:billing_address) }
Expected Purchase to have a has_one association called billing_address (BillingAddress does not exist)
# ./spec/models/purchase_spec.rb:23:in `block (2 levels) in <top (required)>'
It doesn't seem to be detecting that the association is polymorphic. Even in my console:
irb(main):001:0> p = Purchase.new
=> #<Purchase id: nil, user_id: nil, order_date: nil, total_cents: 0, total_currency: "USD", shipping_cents: 0, shipping_currency: "USD", tax_cents: 0, tax_currency: "USD", subtotal_cents: 0, subtotal_currency: "USD", created_at: nil, updated_at: nil, status: nil>
irb(main):002:0> p.shipping_address
=> nil
irb(main):003:0> p.build_shipping_address
NameError: uninitialized constant Purchase::ShippingAddress
What am I doing wrong??