February 7, 2017 | admin | Leave a comment UUID’s I love UUID’s. You should use them. Rails 4 makes it simple to get setup and use UUID’s throughout your project. First, we enable UUID’s: rails g migration enable_uuid_extension This creates the following migration: class EnableUuidExtension < ActiveRecord::Migration def change enable_extension 'uuid-ossp' end end Next, create a model rails g model Book title The Problem Unfortunately, this creates an integer-based primary key migration: class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :title t.timestamps end end end To move forward, you must fiddle with that migration to add id: :uuid to the create_table method: class CreateBooks < ActiveRecord::Migration def change create_table :books, id: :uuid do |t| t.string :title t.timestamps end end end After spending a few weeks on a new project doing this, I figured we could make a change to Rails to allow this to happen. Here’s how. The Solution I recently had a change merged into Rails you should know about. Here’s a look at the original commit, then a follow-up to make a few minor modifications. In application.rb, simply make the following addition: config.generators do |g| g.orm :active_record, primary_key_type: :uuid end Now, whenever you generate a migration, we’ll tag on id: :uuid to the create_table method. Warning You must have already added a UUID extension to your database. If not, running this migration will fail. So don’t forget the rails g migration enable_uuid_extension migration up front. Enjoy! 😀 source: http://blog.mccartie.com/2015/10/20/default-uuid’s-in-rails.html Share this:Click to share on Twitter (Opens in new window)Click to share on Facebook (Opens in new window)Click to share on Google+ (Opens in new window) Related