Skip to content

Instantly share code, notes, and snippets.

@havilchis
Last active April 3, 2017 08:15
Embed
What would you like to do?
How to create a new table with UUID as Primary Key in Rails 5
# This instructions only works whith Postgresql as database.
# ::::::::::::: BEFORE PROCEEDING :::::::::::::::
# You need to know that this feature is included in Rails 5, you don't need to install any gem
# But... you must be capable of enable the extention "plpgsql" in your Database, in other words
# your db user needs root privileges. Check that before wasting time modifying your app.
# if you are deploying in Heroku or Amazon RDS don't worry, they haves tutorials for that.
# :::::::::: create a migration for uuid-oss :::::::::
# Your Schema.rb will look like this
ActiveRecord::Schema.define(version: 20170403072651) do
enable_extension "plpgsql"
enable_extension "uuid-ossp"
# ::::::::::: CREATE NEW TABLE WITH UUID AS PRIMARY KEY ::::::::::::
# Your migration file will look like this, modify it if necessary.
create_table :users, id: :uuid do |t|
t.string :name
end
# ::::::::::: HOW TO REFERENCE TO A TABLE WITH UUID AS PRIMARY KEY (HAS MANY, BELOGS TO...) ::::::::::::
#Run "rails g migration AddSomethingToOtherThing thing:references" normaly
#then modify the migration file in this way...
class AddUserToOrders < ActiveRecord::Migration[5.0]
def change
add_reference :order, :user, type: :uuid, foreign_key: true
end
end
# More info: http://blog.bigbinary.com/2016/04/04/rails-5-provides-application-config-to-use-UUID-as-primary-key.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment