我想以稍微奇怪的方式使用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_type
和addressable_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
这可能吗?还有其他解决方案还是需要重新考虑我的数据库模式?
为了后代的缘故,可能吗?为什么这不可能? – Intentss 2012-10-13 01:22:47