---
title: "Rails 5 provides config to use UUID as primary key"
description:
  "Rails can use UUID as primary key for all the migrations by setting config."
canonical_url: "https://www.bigbinary.com/blog/rails-5-provides-application-config-to-use-UUID-as-primary-key"
markdown_url: "https://www.bigbinary.com/blog/rails-5-provides-application-config-to-use-UUID-as-primary-key.md"
---

# Rails 5 provides config to use UUID as primary key

Rails can use UUID as primary key for all the migrations by setting config.

- Author: Vijay Kumar Agrawal
- Published: April 4, 2016
- Categories: Rails 5, Rails

UUIDs are a popular alternative to auto-incremental integer primary keys.

```ruby

create_table :users, id: :uuid do |t|
  t.string :name
end

```

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](https://github.com/rails/rails/pull/22033).
We need to set primary key as UUID in `config/application.rb`.

```ruby

config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

```

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](https://guides.rubyonrails.org/active_record_postgresql.html#uuid).

To enable [pgcrypto](https://www.postgresql.org/docs/8.3/pgcrypto.html)
extension we need a migration which does something like this.

```ruby
class EnablePgcryptoExtension < ActiveRecord::Migration
  def change
    enable_extension 'pgcrypto'
  end
end
```

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-provides-application-config-to-use-UUID-as-primary-key)
