Skip to content

Instantly share code, notes, and snippets.

@yannvery
Last active April 29, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yannvery/78ae095bdfe1556ff882f8242e47b1e9 to your computer and use it in GitHub Desktop.
Save yannvery/78ae095bdfe1556ff882f8242e47b1e9 to your computer and use it in GitHub Desktop.
Use uuid on Rails with PostgreSQL

Use uuid on rails with PostgreSQL

This guide is a sort of extract of official rails guide: Official rails guide

Here I describe an implementation of uuid with PostgreSQL >= 9.4. This requires to enable pgcrypto

Example with a creation of a table named trackers:

class CreateTrackers < ActiveRecord::Migration[5.0]
  def change
    enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
    create_table :trackers, id: :uuid, default: 'gen_random_uuid()' do |t|
      t.integer :duration, null: false
      t.string  :description, null: false

      t.timestamps
    end
  end
end

You can use uuid to define a relation reference

class CreateProjects < ActiveRecord::Migration[5.0]
  def change
    enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
    create_table :projects, id: :uuid, default: 'gen_random_uuid()' do |t|
      t.string :name
      t.uuid :user_id
      t.timestamps
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment