Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 多个关联到一个多态模型_Ruby_Database_Ruby On Rails 3_Database Design_Activerecord - Fatal编程技术网

Ruby 多个关联到一个多态模型

Ruby 多个关联到一个多态模型,ruby,database,ruby-on-rails-3,database-design,activerecord,Ruby,Database,Ruby On Rails 3,Database Design,Activerecord,我有两种型号,地址和用户: 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",

我有两种型号,
地址
用户

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
类地址
问题是如果我为
用户创建
账单地址
,它将自动设置为
联系人地址
,因为
地址
表没有指定不同的
资源类型
(两者都是
用户
)。 你能给我一些关于如何设置模型的建议吗


谢谢

我想说的是,账单地址更像是一张订单,而不是一个人。例如,在一张订单上,我可能希望你在工作时给我开账单,在家里给我开账单

此外,一个人可以有许多地址,但一个地址也可以有许多人。它是一个网络,而不是层次结构。经典代表:

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

我选择简易方式,为
地址表添加了另一个外键。之后:

has_one :contact_address, class_name: "Address", as: :resource, foreign_key: :foreign_key
我可以帮你。要实现这一点,您必须通过迁移将
类型
列添加到
位置
表中(与所有单表继承模型一样)

类地址

值得一提的是,
所属的关系名(
:resource
)有点奇怪。也许
:可寻址的
更有意义?

据我所知,您不需要进行多态关联。您可以这样做,用户有多个:联系人地址,并且在地址表中有一个标志来指示该地址是账单地址还是联系人地址。如果这是你想要的,我可以详细说明。是的,这可能是一种方式,但我需要这是多态关联:(无论您是否使用多态关联,当前模式在任何情况下都不会工作…现在,如果您未使用多态关联,那么问题将再次存在,因为将在后端触发的SQL查询将是相同的,因为您指定了相同的资源和类。。。
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