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