Using PostgreSQL UUIDs as primary keys with Rails 5.
You can use UUIDs as the primary key on Rails 5 tables in a few simple steps.
Enable the extension.
Before using UUIDs in PostgreSQL, you must first enable the uuid-ossp extension.
If you’re already using UUIDs, you’ve already done this step. To enable the extension, generate a migration.
$ bin/rails g migration enable_uuid_extension
That should generate a migration that looks like this.
class EnableUuidExtension < ActiveRecord::Migration[5.0] def change enable_extension 'uuid-ossp' end end
Add ability to default to uuid as primary key when generating database migrations.
Put this in your config/application.rb file.
config.generators do |g| g.orm :active_record, primary_key_type: :uuid end
Or create a new file at config/initializers/generators.rb. Best practices.
Rails.application.config.generators do |g| g.orm :active_record, primary_key_type: :uuid end
Now, just use rails generate.
$ bin/rails g model User
Now, if you don’t want it as the default for all migrations. Does not ability default UUID.
You can use so for single migration.
bin/rails g model User --primary_key_type=uuid
Do you use UUID as your primary keys? Do you have anything to add? Leave your comment!
That’s all folks, until next time!!!