我想以稍微奇怪的方式使用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