![](/img/trans.png)
[英]Setting up a polymorphic association where associated tables have different primary key types (UUID and Integer)
[英]Polymorphic Association Rails : Different primary_keys types (id & uuid)
我想定義一個多態表。 我的問題是一個表的 primary_key 是uuid(string)
類型,另一個id(integer)
。 我想也許有model_able_id
和model_able_uuid
取決於變model_type
但我不說出來,它可能會打破噸的ActiveRecord的功能多態。
我想到的其他一些事情是使用 STI,但我仍然很困惑,當然,我可以將 ids 遷移到 uuids 並且這可以解決我的問題(但我寧願不這樣做)。
在選項中指定(多態)外鍵的類型。 如果需要,將:string
更改為:uuid
。
create_table :table_name do |t|
t.references :target, type: :string, polymorphic: true, null: false
end
那么字符串和整數target_id
都是可以接受的。
檢查API 文檔。
面臨同樣的問題,目前還沒有官方解決方案,這兩個問題在 rails repo 中是公開的:
https://github.com/rails/rails/issues/33407
https://github.com/rails/rails/issues/33525
在這些問題之一中有一個建議,它對我不起作用(它正在生成兩個連接,由 rails 生成的默認連接導致失敗,而我定義了一個連接)。
我最終根本沒有使用關聯,我定義了一種方法來使用自定義查詢正確獲取實際記錄。 我不需要dependent: destroy
否則我也可以定義一個 before_destroy 方法。
希望它可以幫助某人。
我遇到了完全相同的問題。 我的解決方案將_id
字段的類型修改為字符串。
def change
add_reference :ratings, :rater, polymorphic: true, index: true
change_column :ratings, :rater_id, :string
end
我希望它有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.