Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-on-rails-3.2rails-postgresql

How to set default 'uuid-ossp' extension to all migration files using Rails?


How to set default 'uuid-ossp' extension to all migration files?

enable_extension 'uuid-ossp'

I'm using Ruby 2.1 and Rails 4 and PostgreSQL.


Solution

  • Rails 4 has native support for the type UUID (Universally Unique Identifier) in Postgres. Here I will describe how you can use it for generating UUIDs without doing it manually in your Rails code.

    First you need to enable the Postgres extension ‘uuid-ossp’:

    class CreateUuidPsqlExtension < ActiveRecord::Migration
      def self.up
        enable_extension "uuid-ossp"
      end
    
      def self.down
        disable_extension "uuid-ossp"
      end
    end
    

    You can use a UUID as a ID replacement:

    create_table :translations, id: :uuid do |t|
      t.string :title
      t.timestamps
    end
    

    In this case the Translations table will have a UUID as ID and it is autogenerated. The uuid-ossp extension in Postgresq has different algorithms how the UUID is generated. Rails 4 uses v4 per default. You can read more about these algorithms here: http://www.postgresql.org/docs/current/static/uuid-ossp.html

    However, sometimes you don't want to have the UUID as ID replacement and instead have it in a separate column:

    class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
      def up
        add_column :translations, :uuid, :uuid
      end
    
      def down
        remove_column :translations, :uuid
      end
    end
    

    This will create a UUID column, but the UUID will not be autogenerated. You have to do it yourself in Rails with SecureRandom. However, we think that this is a typical database responsibility. Fortunately, the default option in add_column helps:

    class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
      def up
        add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
      end
    
      def down
        remove_column :translations, :uuid
      end
    end
    

    Now the UUID will be created automatically, also for existing records!

    I hope this help you to understand.. If this post satisfied you to understand UUID then kindly up-vote this answer... ;) via Helmut