2012-10-24 37 views
1

我有两个型号,AddressUser多HAS_ONE关联到一个多态模型

class Address < ActiveRecord::Base 
    belongs_to :resource, polymorphic: true 
end 

class User < ActiveRecord::Base 
    has_one :contact_address, class_name: "Address", as: :resource 
    has_one :billing_address, class_name: "Address", as: :resource 
end 

问题是,如果我创建billing_addressUser它会自动设置为contact_address,因为addresses表没有指定不同的resource_type(均为User)。 你可以给我一些关于如何设置我的模型的建议吗?

谢谢

+0

从我所理解的,你不需要做多态关联。你可以做一些事情,比如用户has_many:contact_address,并在地址表中有一个标记来表示该地址是否是账单地址,或者只是一个联系地址。我可以详细说明,如果这是你正在寻找的。 –

+0

是的,这可能是一种方式,但我需要这是多态的关联:( –

+0

当前的模式不会在任何情况下工作,无论你使用多态还是不...现在,如果你没有使用多态关联,那么再次问题将持续,因为在后端将被触发的SQL查询将是相同的,因为你已经指定了相同的资源和类... –

回答

0

我选择简单的方法,为addresses表添加了另一个foreign_key。之后:

has_one :contact_address, class_name: "Address", as: :resource, foreign_key: :foreign_key 
0

我会说一个帐单地址是一个比一个人更多的命令。例如,在一个订单上,我可能希望你在工作时给我打电话,另一个在家。

此外,一个人可以有很多地址,但地址也可以有很多人。它是一个网络,而不是一个等级。经典的代表:

PARTY 
id 
type 
name 

PARTY_ADDRESS 
id 
party_id 
address_id 
type {home, work} 

ADDRESS 
id 
suite 
... 

ORDER 
id 
date 
customer_party_address_id 
bill_to_party_address_id 

ORDER_ITEM 
id 
order_id 
product_id 
price 
quantity 
ship_to_party_address_id 
0

Single table inheritance可以帮助你。为了实现这一点,您必须通过迁移(与使用所有单表继承模型一样)将type列添加到locations表中。

class Address < ActiveRecord::Base 
    belongs_to :resource, polymorphic: true 
end 

class ContactAddress < Address 
end 

class BillingAddress < Address 
end 

class User < ActiveRecord::Base 
    has_one :contact_address, as: :resource 
    has_one :billing_address, as: :resource 
end 

对于它的价值,在belongs_to关系的域名(:resource)是有点怪。也许:addressable会更有意义?