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

Time:06-28

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?

CodePudding user response:

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

I hope that this helps

CodePudding user response:

MZaragoza's answer is great when you are using PostgreSQL because gen_random_uuid is PostgreSQL specific.

When you use another database or want to be database agnostic then you might want to consider generating the UUID in the model before saving a record into the database like this:

# in the migration 
add_column :addresses, :uuid, :uuid

# in app/models/address.rb
before_save :generate_uuid

private
def generate_uuid
  self.uuid = SecureRandom.uuid
end
  • Related