[英]Change type identifier in polymorphic association
I'm trying to use Rails's polymorphic associations in a slightly odd way and I'm running into a problem. 我试图以一种有点奇怪的方式使用Rails的多态关联,我遇到了一个问题。
The polymorphic table is Address
多态表是
Address
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
I have a uniqueness constraint on my database so that the same address address association can't be added twice. 我的数据库有唯一性约束,因此无法添加相同的地址关联两次。
I also have a Trip
model which needs two addresses. 我也有一个需要两个地址的
Trip
模型。 One is the trip's origin and the other is it's destination. 一个是旅行的起源,另一个是旅行目的地。
class Trip < ActiveRecord::Base
has_one :origin, as: :addressable, class_name: 'Address'
has_one :destination, as: :addressable, class_name: 'Address'
end
The problem is that when Rails creates an address which is associated with a trip, it uses the class name (which is "Trip") to fill in the addressable_type
column. 问题是当Rails创建一个与trip相关联的地址时,它使用类名(即“Trip”)来填充
addressable_type
列。 That means that if I try to make a trip with an origin and destination, rails attempts to add two rows with the same addressable_type
and addressable_id
. 这意味着如果我尝试使用origin和destination进行旅行,rails会尝试使用相同的
addressable_type
和addressable_id
添加两行。 This obviously fails at the uniqueness constraint. 这显然在唯一性约束下失败了。
I could remove the uniqueness constraint but then I would just end up with duplicated records which would confuse Rails because it wouldn't know which record was the origin and which was the destination. 我可以删除唯一性约束,但之后我会最终得到重复的记录,这会混淆Rails,因为它不知道哪个记录是起源,哪个是目的地。
What I would really like to do is specify the string to use for addressable_type
: 我真正想要做的是指定用于
addressable_type
的字符串:
class Trip < ActiveRecord::Base
has_one :origin, as: :addressable, class_name: 'Address', type: 'Trip Origin'
has_one :destination, as: :addressable, class_name: 'Address', type: 'Trip Destination'
end
Is that possible? 那可能吗? Is there another solution or do I need to rethink my database schema?
是否有其他解决方案或我是否需要重新考虑我的数据库架构?
I would have thought that address
shouldn't belongs_to
a trip, since one address might be the origin and/or destination of multiple trips. 我原以为
address
不应该belongs_to
旅行,因为一个地址可能是多次旅行的起源和/或目的地。 This is especially true if you have a uniqueness constraint. 如果您有唯一性约束,则尤其如此。 The foreign key should be stored in the trip:
外键应存储在行程中:
class Address < ActiveRecord::Base
has_many :trips_as_origin, class_name: "Trip", foreign_key: "origin_id"
has_many :trips_as_destination, class_name: "Trip", foreign_key: "destination_id"
end
class Trip < ActiveRecord::Base
belongs_to :origin, class_name: "Address"
belongs_to :destination, class_name "Address"
end
You would need to create a migration that adds origin_id
and destination_id
to Trip
. 您需要创建一个将
origin_id
和destination_id
添加到Trip
的迁移。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.