With this gem you can use UUID instead of id in routes. But id is still primary key.
Add this line to your application's Gemfile:
gem 'uuidable'And then execute:
$ bundle
Or install it yourself as:
$ gem install uuidable
Simply add uuidable in your ActiveRecord model:
class Project < ActiveRecord::Base
uuidable
# Rest of the code
endYou can use special methods in migrations:
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.uuid
#...
end
# Or
add_uuid_column :projects
end
endNew UUID columns store 16 bytes (varbinary(16)). Versions before 1.0 stored the 36-character text form (varbinary(36)). Models read both as UUID strings (16-byte columns are recognized by uuid in their name), and upgrading the gem does not change existing columns.
Choose the format of a new column with storage::
t.uuid storage: :text
add_uuid_column :projects, :parent_uuid, storage: :binaryAn app that keeps its pre-1.0 columns can make text the default, so that new columns match the existing ones:
# config/initializers/uuidable.rb
Uuidable.default_storage = :textMigrations read the setting when they run, so set it before the first migration on 1.x runs, and keep it: a database built from scratch with another setting gets other column types. Migrations that pass storage: or limit: do not depend on it.
Columns compared in SQL, for example in a join, must use the same storage: a 16-byte UUID never equals its 36-character text form.
Converting existing columns is optional. On MySQL 8, include the helpers in a migration:
class ConvertProjectUuids < ActiveRecord::Migration[7.2]
include Uuidable::V1MigrationHelpers
def change
# Every 36-byte column with `uuid` in its name, or only the listed ones:
uuidable_migrate_uuid_columns_to_v1 :projects
uuidable_migrate_uuid_columns_to_v1 :tasks, { 'project_uuid' => {} }
end
endThe original values stay in *__old columns, which models keep writing while they exist, so the migration can be rolled back. A model callback that sets a converted UUID has to run before that copy: a before_create or before_update declared after the model's schema has loaded runs after it, so use before_save there. When you no longer need the old values, drop them with uuidable_drop_all_pre_v1_uuid_columns!: it drops every *__old column with uuid in its name in all tables, and cannot be undone.
- A converted column keeps the nullability and comment of the original; override them with
null:andcomment:in its options. Its default is not carried over; a rollback restores it. - An empty string becomes
NULL. A column that ends upNOT NULLwith empty orNULLvalues is refused. - A listed column that is not a 36-byte UUID column raises an error; pass
skip_type_check: trueto convert a column of another type, such asvarchar(36). A listed column that is 16 bytes already is skipped, also withskip_type_check: true. On Ruby 2.7, use string keys in the list or pass a keyword after it. - Each step is a single
ALTER TABLE. If a call fails, for example on a value that is not a UUID or on two UUIDs that differ only in case under a unique index, its table is left unchanged. Should the cleanup fail as well, drop the remaining*__newcolumn before running it again. - MySQL commits each step, so a migration with several calls can stop halfway. Fix the data and run it again: the columns it already converted are skipped.
- Without a column list a call covers the whole table, and so does its rollback: it restores the columns that earlier migrations converted too, even if the call found nothing left to convert. In
changesuch a call is refused when the table is already partly converted, even by an earlier call of the same migration, so convert listed columns and then the rest of a table inupanddown. Inchange, list only the columns that migration converts, as its rollback restores every listed one. - A rollback written in
changeis reverted by a conversion without options, which without a list takes every remaining 36-byte column; write such rollbacks inupanddown. - Rows written during the conversion are converted too, but adding the converted columns rebuilds the table and blocks writes meanwhile. Restart the application afterwards: running processes keep the old column types.
- Indexes keep their options and expressions; an invisible index comes back visible. Columns that are part of a primary or foreign key are refused; drop the key first. Convert the source of a generated column rather than the column itself, and drop a unique index on a prefix of a UUID before converting it.
- A rollback is refused if rows changed without the model callbacks, for example with
update_all, because the*__oldcolumns miss those changes. The check runs just before the rollback, so stop such writes while it runs. Inserts that skip callbacks, such asinsert_all, fail while aNOT NULL*__oldcolumn exists.
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
Specs that need a database are skipped unless UUIDABLE_DATABASE_URL points to a MySQL 8 database whose name ends in _test. The specs create and drop their own tables. To run them against a specific Active Record version:
BUNDLE_GEMFILE=gemfiles/activerecord.gemfile ACTIVE_RECORD_VERSION='~> 8.1.0' \
UUIDABLE_DATABASE_URL=mysql2://root@127.0.0.1:3306/uuidable_test bundle exec rake
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/flant/uuidable.
The gem is available as open source under the terms of the MIT License.