我有两个模型,Purchase
和Address
。我正在努力使Address
多态,以便我可以在我的Purchase模型中将其重用于has_one :billing_address
和has_one :shipping_address
:
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
class Purchase < ActiveRecord::Base
has_one :shipping_address, -> { where(addressable_type: "shipping_address") }, class_name: Address, as: :addressable
has_one :billing_address, -> { where(addressable_type: "billing_address") }, class_name: Address, as: :addressable
end
但是,当我转到控制台并尝试为purchase
构建新的送货地址时,它不会使用我的条件生成实例。我以为-> { where(addressable_type: "shipping_address") }
会使用“shipping_address”预填充addressable_type列吗?
这就是我的意思:
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.build_shipping_address
=> #<Address id: nil, first_name: nil, last_name: nil, street_address: nil, street_address2: nil, zip_code: nil, phone_number: nil, created_at: nil, updated_at: nil, state_id: nil, city: nil, addressable_type: "Purchase", addressable_id: nil>
irb(main):003:0> p.save
(0.3ms) SAVEPOINT active_record_1
SQL (0.5ms) INSERT INTO `purchases` (`created_at`, `updated_at`) VALUES ('2014-06-04 15:06:55', '2014-06-04 15:06:55')
SQL (0.2ms) INSERT INTO `addresses` (`addressable_id`, `addressable_type`, `created_at`, `updated_at`) VALUES (9, 'Purchase', '2014-06-04 15:06:55', '2014-06-04 15:06:55')
(0.2ms) RELEASE SAVEPOINT active_record_1
=> true
irb(main):004:0> p.shipping_address
=> #<Address id: 10, first_name: nil, last_name: nil, street_address: nil, street_address2: nil, zip_code: nil, phone_number: nil, created_at: "2014-06-04 15:06:55", updated_at: "2014-06-04 15:06:55", state_id: nil, city: nil, addressable_type: "Purchase", addressable_id: 9>
irb(main):005:0> p.reload
Purchase Load (0.6ms) SELECT `purchases`.* FROM `purchases` WHERE `purchases`.`id` = 9 LIMIT 1
=> #<Purchase id: 9, 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: "2014-06-04 15:06:55", updated_at: "2014-06-04 15:06:55", status: nil>
irb(main):006:0> p.shipping_address
Address Load (0.5ms) SELECT `addresses`.* FROM `addresses` WHERE `addresses`.`addressable_id` = 9 AND `addresses`.`addressable_type` = 'Purchase' AND `addresses`.`addressable_type` = 'shipping_address' LIMIT 1
=> nil
注意它没有设置addressable_type列。我该如何解决这个问题?