Uuid in Rails

Jr Medina
3 min readMay 17, 2021

I have been on a learning journey involving Ruby on Rails for a few weeks now. I have learned a few things along the way and I am expecting to continue learning this framework, as it continues to capture my attention the further I dive.

One of the things I have learned is using a Uuid (Universally Unique Identifiers) as the ID’s for any models crated in my Rails app. One would use this to make it impossible for anyone to see how big your database is based on endpoints. This is also used when there are many relationships between models and it would make it so no duplicate ID’s would be made between different models in the database.

One way to do this is to enable Uuid in your Rails application. I have now started to use postgresql as my database and do not plan on going back. In order to enable the Uuid, you need to run the migration below.

Within the migration, you want to enable “pgcrypto” in your migration as shown below. you want to enter “enable_extension ‘pgcrypto’.

Be sure to run a migration to get this into your schema. Once this is done you should see the ‘pgcrypto’ extension referenced in your schema.

Now, you are able to modify your models to set the ID to be a Uuid. You can run the normal command to set up your model with the attributes needed. I have created a bank model that has attributes of name and location.

Now, I will modify this table to include a Uuid by altering the third line in the file.

With this done, I can run a migration command that will include all I need in my schema for this table.

This screenshot shows that the Uuid will default to a unique identifier. And when I open up a console and run Bank.all after seeding in a bank I get a Uuid as the ID.

There are many ways to do this and this, I have found has been the simplest way to add this in to take over the ID for any circumstance.

--

--

Jr Medina

Soon-to-be Flatiron School Successor, with an enthusiasm towards Front-End Web Development, lifelong learning, and continuous improvement.