这些关系是多态关联的良好候选者吗?

时间:2013-07-24 16:11:26

标签: ruby-on-rails ruby

我有订单,地址和用户模型。订单可以包含结算和送货地址。用户可以拥有许多已保存的地址。将Address模型用于所有事情是有意义的。我关注的是订单和开票/送货地址关系。

我不确定这是否适用于多态关联。

class Order
  has_one :billing_address,  as: :addressable, polymorphic: true
  has_one :shipping_address, as: :addressable, polymorphic: true
end

class User
  has_many :addresses, as: :addressable, polymorphic: true
end

class Address
  belongs_to :addressable, polymorphic: true
end

我是否正确建模?人们通常如何在Rails中解决这个问题?

我可以将订单belongs_to :billing_addressshipping_address反转,但这意味着在地址模型中有一个冗余的user_id

3 个答案:

答案 0 :(得分:0)

您还需要在混合中添加单表继承。使用BillingAddress和ShippingAddress的子类地址并适当地调整订单模型关联,你应该没问题。

一定要测试一下。有(或者是)一些奇怪的情况,多态+ sti返回错误的表类型。我的记忆是你可能还想要一个用户可以拥有许多的MailingAddress,以便没有任何顶级地址。

答案 1 :(得分:0)

我不会在这里使用多态关联。相反,请为您的Address模型指定一个字段,指明它是什么类型的地址;并为您的Order模型提供两个具有相同类但条件不同的字段:

class Order < ActiveRecord::Base
  has_one :billing_address, :class => "Address", :conditions => "addr_type = 'billing'"
  has_one :shipping_address, :class => "Address", :conditions => "addr_type = 'shipping'"
end

class User < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :order
  belongs_to :user
end

答案 2 :(得分:0)

:billing_address和:shipping_address将具有相同的外键类型Order,因此您将遇到问题。

有一个很好的堆栈溢出问题解决了类似的问题......最好的答案表明你可能想要使用不同的技术(即不是多态关联)

Why can you not have a foreign key in a polymorphic association?

我在解决他的“超级”解决方案时遇到了一些麻烦,但“扭转关系”提案看起来很干净且很容易实现