我的公司模型如下所示:
class Company < ActiveRecord::Base
has_one :visiting_address, -> { where "addressable_type = 'visiting_address'" }, as: :addressable, class_name: "Address", dependent: :destroy
has_one :billing_address, -> { where "addressable_type = 'billing_address'" }, as: :addressable, class_name: "Address", dependent: :destroy
has_one :delivery_address, -> { where "addressable_type = 'delivery_address'" }, as: :addressable, class_name: "Address", dependent: :destroy
def visiting_address=(address)
super
address.update_attribute(:addressable_type, "visiting_address")
end
def delivery_address=(address)
super
address.update_attribute(:addressable_type, "delivery_address")
end
def billing_address=(address)
super
address.update_attribute(:addressable_type, "billing_address")
end
end
我有我的地址模型:
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
一切似乎都正常,但事实并非如此。我解雇了&#39; rails c&#39;并尝试创建一些模型并关联它们。它工作,所以我去保存数据库和退出控制台中的事务。我再次点击它并获取公司并尝试访问帐单地址,但我总是没有。
我可以看到正在执行的查询,这是错误的:
SELECT "addresses".* FROM "addresses" WHERE "addresses"."addressable_id" = ? AND "addresses"."addressable_type" = ? AND (addressable_type = 'billing_address') LIMIT 1 [["addressable_id", 1], ["addressable_type", "Company"]]
为什么要进行该查询,但在我保存并退出之前,当我打电话给c.billing_address时,我得到了正确的地址,现在它没有了。 任何人都可以帮助我吗?