Rails:我可以使用非整数主键的多态引用吗?

时间:2011-01-19 15:30:31

标签: ruby-on-rails activerecord foreign-keys uuid

我有一个使用UUID作为主键的数据库,如下所示:

create_table "my_table", :id => false, :force => true do |t|
 t.string "id", :limit => 36
end

但是,当我尝试使用:对该表的外键的引用时,它会为ID生成整数列。可以:指示引用处理非整数ID吗?我对引用表的迁移是这样的:

create_table "child_table" :id => false, :force => true do |t|
 t.string "id", :limit => 36
 t.references :my_table
end

我知道我可以手动创建:my_table_id:my_table_type列,但我想知道:references是否可以在这种情况下发挥其魔力,这样我就不会我必须在整个代码中明确地处理id +类型。

2 个答案:

答案 0 :(得分:17)

A:自Rails 4.2引用时添加了类型选项

t.references :car, type: :uuid, index: true

例如:

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

来源:https://github.com/rails/rails/pull/16231

答案 1 :(得分:3)

Nope,references在撰写本文时仅创建整数列。

我确信您可以覆盖references方法来执行您想要的操作。但IMO最好明确指定UUID列并键入列。这样,代码就可以清楚地了解幕后发生的事情。