Protect Your Database IDs in Rails with UUID
For most backend developers, protecting the database from hackers is at the top of the priority list. All it takes is one bad actor getting access to information they shouldn’t have, and you’re screwed.
In SQL databases, one potential vulnerability is the fact that in many databases, the primary key, or ID, for each data entry is just an integer that increments by 1. So if a hacker wants to access some random record, they can just try random integers and see what happens.
UUID, which generates random strings of letters and numbers, is a great way to prevent that problem. Instead of using simple integers that increase by 1 each time, your database IDs look more like this:
Much harder to guess.
So if you’re looking for some peace of mind, here’s how to get UUID primary keys up and running with a Rails backend and a PostgreSQL database.
If you haven’t yet, first start your new project on the command line with
rails new my-app -d=postgresql, replacing my-app with the project name of your choice.
Next, before you create any other migrations, type
rails g migration enable_uuid in the command line. That should add a new migration file to the
In that new file, under def change, add
Then, to actually use UUID strings for your primary keys, go to
config/initializers and create a
generators.rb file if you don’t already have one. Then type:
Rails.application.config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
Now you’re ready to generate any future migrations and models you might need! Create them the way you normally would, and their IDs will automatically be formatted as UUIDs.
And you can breathe just a tiny bit easier knowing that your primary keys are now much harder to guess.