Rails 4 has native support for the type UUID (Universally Unique Identifier) in Postgres. In this Div Bit I will describe how you can use it for generating UUIDs without doing it manually in your Rails code.
First you need to enable the Postgres extension 'uuid-ossp':
class CreateUuidPsqlExtension < ActiveRecord::Migration
def self.up
enable_extension "uuid-ossp"
end
def self.down
disable_extension "uuid-ossp"
end
end
You can use a UUID as a ID replacement:
create_table :translations, id: :uuid do |t|
t.string :title
t.timestamps
end
In this case the Translations table will have a UUID as ID and it is autogenerated. The uuid-ossp extension in Postgresq has different algorithms how the UUID is generated. Rails 4 uses v4 per default. You can read more about these algorithms here: http://www.postgresql.org/docs/current/static/uuid-ossp.html
However, sometimes you don't want to have the UUID as ID replacement and instead have it in a separate column:
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
def up
add_column :translations, :uuid, :uuid
end
def down
remove_column :translations, :uuid
end
end
This will create a UUID column, but the UUID will not be autogenerated. You have to do it yourself in Rails with SecureRandom. However, we think that this is a typical database responsibility. Fortunately, the default option in add_column helps:
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
def up
add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
end
def down
remove_column :translations, :uuid
end
end
Now the UUID will be created automatically, also for existing records!