kdt*_*kdt 6 uuid activerecord ruby-on-rails foreign-keys
我有一个使用UUID作为主键的数据库,如下所示:
create_table "my_table", :id => false, :force => true do |t|
t.string "id", :limit => 36
end
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用:对该表的外键的引用时,它会为ID生成整数列.可以:指示引用处理非整数ID吗?我对引用表的迁移是这样的:
create_table "child_table" :id => false, :force => true do |t|
t.string "id", :limit => 36
t.references :my_table
end
Run Code Online (Sandbox Code Playgroud)
我知道我可以手动创建:my_table_id和:my_table_type列,但我想知道是否:references可以在这些情况下做它的魔术,这样我就不必在我的代码中显式处理id +类型.
Dan*_*Wit 17
A:自Rails 4.2引用时添加了类型选项
t.references :car, type: :uuid, index: true
Run Code Online (Sandbox Code Playgroud)
例如:
def change
enable_extension 'uuid-ossp'
create_table :cars, id: :uuid do |t|
t.integer :seats
# And other car-specific things
end
create_table :wheels do |t|
t.references :car, type: :uuid, index: true
t.integer :radius
# And other wheel-specific things
end
end
Run Code Online (Sandbox Code Playgroud)
来源:https://github.com/rails/rails/pull/16231
不,references截至撰写本文时仅创建整数列。
我确信您可以重写该references方法来执行您想要的操作。但在我看来,您最好明确指定 UUID 列并键入列。这样代码就可以清楚地了解幕后发生的事情。
| 归档时间: |
|
| 查看次数: |
2336 次 |
| 最近记录: |