Rails: 一个模型需要多次多态关系。如何区分?有没有更好的办法?

Rails: Polymorphic Relationship needed multiple times for one model. How to differentiate? Is there a better way?

我有一个复杂的关系,我有多个模型需要地址。这通常意味着使用像这样的多态关系:

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true
end

class User < ApplicationRecord
  # no issue, its "addressable" so just use this line of code
  has_one :address, as: :addressable
end

class Account < ApplicationRecord
  # Ok the issue here is that I need exactly TWO addresses though
  # One is for billing and one if a physical address where an event will
  # physically take place.
  has_one :billing_address, class_name: "Address", as: :addressable
  has_one :site_address, class_name: "Address", as: :addressable
end

问题是...

a = Account.first
a.billing_address #returns an address
a.site_address #returns the same address

如何让帐户区分两个地址?我知道这实际上不是多态性的限制,而是我需要解决的软件设计问题。我想知道我是否需要将 Address 视为抽象模型并从中派生 BillingAddressSiteAddress 并且可能有这样的东西:

class Address < ApplicationRecord
  # see active_record-acts_as gem for how this mixin works
  # https://github.com/hzamani/active_record-acts_as
  actable
  belongs_to :addressable, polymorphic: true
end

class User < ApplicationRecord
  # no issue, its "addressable" so just use this line of code
  has_one :address, as: :addressable
end

class BillingAddress < ApplicationRecord
  acts_as :address
end

class SiteAddress < ApplicationRecord
  acts_as :address
end

class Account < ApplicationRecord
  has_one :billing_address
  has_one :site_address
end

这样做可能很好,因为我还有一个 Event 模型,它需要一个站点地址,所以我也可以这样做:

class Event < ApplicationRecord
  has_one :site_address
end

这是工程过度了吗?冒着听起来过于主观的风险,您对此有何看法?有更好的方法吗?

地址类别之间的区别是什么?您提到您可能有账单地址和网站地址。

例如,如果类别由名为 'category' 的属性确定,那么您所要做的就是在可寻址的关联声明上设置条件:

class Account < ApplicationRecord
  has_one :billing_address, -> { where category: 'billing' }, class_name: "Address", as: :addressable
  has_one :site_address, -> { where category: 'site' }, class_name: "Address", as: :addressable
end