Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Migrations with UUID primary key

In the migration that I want to create, the primary key of the table is a field called "id" but it is not an auto-incrementing integer. It's datatype should be uniqueidentifier (a uuid). Here is what I have tried:

create_table :some_things, :id => false do |t|
  t.column :id, :uniqueidentifier, :primary => true
  t.column :name, :string, :limit => 255
  t.column :type, :tinyint
  t.column :deleted_flag, :bit
  t.column :class_id, :uniqueidentifier
  t.timestamps
end

This creates the table alright, but there is no primary key (because I said :id=>false). If I said "create_table :some_things, :id => true, :primary => :id", then "id" becomes the primary key, but it is an auto-incrementing integer, not a non-auto-incrementing uuid.

How can I make this migration work so that the primary key is a field called "id" of type "uniqueidentifier" (non-auto-incrementing)?

I'm using: SQL Server 2008, Rails/ActiveRecord 3.0.3, the activerecord-sqlserver-adapter gem, and an ODBC connection.

like image 835
Mark Avatar asked Feb 14 '11 19:02

Mark


1 Answers

I don't know how to solve problem directly, but I've got a workaround.

Put in your migration column id without 'primary' directive. And after method 'create_table' in migration execute SQL's add constraint

execute "ALTER TABLE some_things ADD PRIMARY KEY (id);"

(don't use MSSQL and may be mistake in SQL-syntax for it)

In your model define primary key by adding

self.primary_key = "id"

or

set_primary_key :id
like image 195
dmr Avatar answered Sep 25 '22 00:09

dmr