【问题标题】:Multiple has_one association to one polymorphic model多个 has_one 关联到一个多态模型
【发布时间】:2012-10-14 14:07:26
【问题描述】:

我有两个模型,AddressUser

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

问题是如果我为User 创建billing_address,它将自动设置为contact_address,因为addresses 表没有指定不同的resource_type(两者都是User)。 您能给我一些关于如何设置模型的建议吗?

谢谢

【问题讨论】:

  • 据我了解,您不需要做多态关联。您可以执行类似用户 has_many :contact_address 的操作,并在地址表中有一个标志来表示该地址也是帐单地址还是只是联系地址。如果这是您正在寻找的,我可以详细说明。
  • 是的,这可能是一种方式,但我需要这是多态关联:(
  • 无论您是否使用多态,当前模式在任何情况下都不起作用......现在如果您不使用多态关联,那么问题将再次存在,因为将触发的 SQL 查询后端将是相同的,因为您指定了相同的资源和类...

标签: ruby database ruby-on-rails-3 database-design activerecord


【解决方案1】:

我会说帐单地址更多地与订单有关,而不是与人有关。例如,在一份订单上,我可能希望您在工作时向我收费,在家里再向我收费。

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      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 会更有意义?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-05
        相关资源
        最近更新 更多