Adding UUID column to Rails and Postgresql table
Most articles in the internet talks about using UUID as a replacemenet for ID, however sometimes you want to use UUID as an extra column, it depends on the use-case, but doing this is easy!

First we need to generate the following migration:

rails g migration enable_uuid

class EnableUuid < ActiveRecord::Migration[6.0]

def change

enable_extension 'pgcrypto'

end

end

Then you can simply add a new column (UUID type) to your existing table:

rails g migration addCustomColumnToTable

and add your custom column:

add_column :custom_column, :uuid, :uuid

Setting the UUID column can be done either via code:

your_model.customo_column = SecureRandom.uuid

or you can let the database generates it for you by default, in this case you have to consider adding a default value when you create the migration we saw before:

add_column :custom_column, :uuid, :uuid, default: "gen_random_uuid()"

Congrats! mission completed!

**Note: above we used pgcrypto extension, which seems to be the recommended one by postgresql doc, another extension that exists (you may see other people using it) is uuid-ossp in case you want to use it change the extension when generate the first migration to:

enable_extension "uuid-ossp"

then when adding a column, the default should be uuid_generate_v4() instead of gen_random_uuid()

add_column :custom_column, :uuid, :uuid, default: "uuid_generate_v4()"

The difference between the 2 extensions? all I know is that pgcrypto is recommended, but feel free to ask google for more info :)

Best!
['Med Bouzid']
['Rails', 'Uuid', 'Postgresql']