Search code examples
ruby-on-railsrubyuuid

Ruby on Rails - How can I use UUID as a simple column in my project?


I want to use UUID as a column from the table Address, but I don`t want to use it as a primary key. Is it possible? How can I do it?


Solution

  • To use UUID the first thing you need to do is to enable it on a migration

    rails g migration EnableUUID

    class EnableUuid < ActiveRecord::Migration[7.1]
      def change
        enable_extension 'pgcrypto'
      end
    end
    

    Now we have to run migrations rake db:migrate

    Now you can create a new field

    rails g migration AddUuidToUsers

    class AddUuidToUsers < ActiveRecord::Migration[7.1]
      def change
        add_column :users, :uuid, :uuid, default: "gen_random_uuid()", null: false
      end
    end
    

    For non PG databases please look at the post by spickermann I hope that this helps