3

我想以稍微奇怪的方式使用Rails的多态关联,并且遇到问题。在多态关联中更改类型标识符

多态表Address

class Address < ActiveRecord::Base 
    belongs_to :addressable, polymorphic: true 
end 

我有我的数据库中的唯一性约束,使同一地址地址的关联不能被添加两次。

我也有一个Trip模型,它需要两个地址。一个是旅程的起源,另一个是目的地。

class Trip < ActiveRecord::Base 
    has_one :origin, as: :addressable, class_name: 'Address' 
    has_one :destination, as: :addressable, class_name: 'Address' 
end 

的问题是,当滑轨创建其与跳闸相关联的地址,它使用类名(这是“跳闸”)来填充addressable_type柱。这意味着,如果我尝试使用原点和目的地进行旅行,rails会尝试添加两行,分别是addressable_typeaddressable_id。这显然在唯一性约束上失败。

我可以删除唯一性约束,但然后我会结束重复的记录,这会混淆Rails,因为它不知道哪个记录是来源,哪个记录是目的地。

我真的很想做的是指定字符串使用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 

这可能吗?还有其他解决方案还是需要重新考虑我的数据库模式?

+0

为了后代的缘故,可能吗?为什么这不可能? – Intentss 2012-10-13 01:22:47

回答

2

我原以为address不应该belongs_to一次旅行,因为一个地址可能是多次旅行的起源和/或目的地。如果您有唯一性约束,则尤其如此。外键应存放在行程:

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 

你需要创建一个迁移,增加了origin_iddestination_idTrip

+0

是的,这是我怀疑自己。谢谢。 – 2012-07-17 14:53:04