This blog is part of our Rails 5 series.
UUIDs are a popular alternative to auto-incremental integer primary keys.
1 2create_table :users, id: :uuid do |t| 3 t.string :name 4end 5
Notice that id: :uuid is passed to create_table. This is all we need to do to have UUID as primary key for users.
Now, if an application is designed to use UUID instead of Integer, then chances are that new tables too would use UUID as primary key. And it can easily get repetitive to add id: :uuid in create_table , every time a new model is generated.
Rails 5 comes up with a solution. We need to set primary key as UUID in config/application.rb.
1 2config.generators do |g| 3 g.orm :active_record, primary_key_type: :uuid 4end 5
This automatically adds id: :uuid to create_table in all future migrations.
If we are using the latest version of PostgreSQL then we should enable pgcrypto extension as per Rails guide.
To enable pgcrypto extension we need a migration which does something like this.
1class EnablePgcryptoExtension < ActiveRecord::Migration 2 def change 3 enable_extension 'pgcrypto' 4 end 5end