簡體   English   中英

在多態關聯中更改類型標識符

[英]Change type identifier in polymorphic association

我試圖以一種有點奇怪的方式使用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

問題是當Rails創建一個與trip相關聯的地址時,它使用類名(即“Trip”)來填充addressable_type列。 這意味着如果我嘗試使用origin和destination進行旅行,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

那可能嗎? 是否有其他解決方案或我是否需要重新考慮我的數據庫架構?

我原以為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_id添加到Trip的遷移。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM