0

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?

  • 1
    Ruby on Rails supports [UUID database columns](https://guides.rubyonrails.org/v5.0/active_record_postgresql.html#uuid). That means you can simply add a column of that type to the table in the same way as adding columns of other types. – spickermann Jun 27 '22 at 19:33
  • Ok, but how can I create a new uuid every time I create a new instance? (I'm new to programming, so thanks for the help!) I tried to use default: "uuid_generate_v4()" in the migration, but it's not working. – Vinicius Köhler Jun 27 '22 at 19:44
  • @ViniciusKöhler what do you mean "not working"? Can you verify the function works (outside of rails)? If not maybe this post can help: https://stackoverflow.com/questions/22446478/extension-exists-but-uuid-generate-v4-fails – engineersmnky Jun 27 '22 at 20:52

2 Answers2

1

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

MZaragoza
  • 10,108
  • 9
  • 71
  • 116
1

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
spickermann
  • 100,941
  • 9
  • 101
  • 131