Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: can I use polymorphic references with non-integer primary keys?

I have a database that uses UUIDs as primary keys, like this:

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

However, when I try to use :references for foreign keys to that table, it generates integer columns for the ID. Can :references be instructed to deal with a non-integer ID? My migration for the referring table is like this:

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

I know that I could just manually create :my_table_id and :my_table_type columns, but I'm wondering whether :references can be made to do its magic under these circumstances so that I don't have to handle the id+type explicitly throughout my code.

like image 401
kdt Avatar asked Jan 19 '11 15:01

kdt


1 Answers

A :type option has been added when referencing since Rails 4.2

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

For example:

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

source: https://github.com/rails/rails/pull/16231

like image 60
Daniël de Wit Avatar answered Nov 03 '22 00:11

Daniël de Wit