让一个用户和事件模型。
我想在这些用例中添加一个地址模型:
在Rails中处理此类用例的最简单方法是什么? 还是有什么宝石可以处理?
答案 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
关于不同类型的地址,使用不同的验证策略和方法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
那样思考,并获取事件的所有地址及其关联的类型。