使用多态方法具有多个地址类型和与模型的关联吗?

时间:2019-03-28 15:38:17

标签: ruby-on-rails

让一个用户和事件模型。

我想在这些用例中添加一个地址模型:

  • 地址具有不同的类型,例如BillingAddress,DeliveryAddress等(我应该使用继承吗?)
  • 用户可以具有多个不同类型的地址。例如,一个用户可以有2个帐单地址和3个收货地址。
  • 事件还可以具有多个不同类型的地址。

在Rails中处理此类用例的最简单方法是什么? 还是有什么宝石可以处理?

1 个答案:

答案 0 :(得分:1)

多态

在地址模型中,如果进行了正确的迁移,则可以使用polymorphic association来使地址属于不同的父模型:

arr = 
[[1 1 0 0 0 0 0 0 1 0]
 [1 1 0 0 0 0 0 1 1 1]
 [0 1 1 0 0 0 0 0 0 0]
 [0 1 1 0 0 0 0 0 0 0]
 [0 1 1 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]

数据迁移

您只需执行以下操作

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

class User < ApplicationRecord
  has_many :addresses, as: :addressable
end

class Event < ApplicationRecord
  has_many :addresses, as: :addressable
end

如果您想手动进行操作,则多态关联会在两者上简单地添加id,类型和索引:

$ rails g migration AddAddressableToAddresses addressable:references:polymorphic

单表继承(STI)

关于不同类型的地址,使用不同的验证策略和方法Single Table Inheritance can be a solution。您将能够像def change add_column :addresses, :addressable_id, :integer add_column :addresses, :addressable_type, :string add_index :addresses, [:addressable_id, :addressable_type] end 那样思考,并获取事件的所有地址及其关联的类型。