Ruby on Rails
January 20, 2021
A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. Sometimes it is referred to as a 'globally unique identifier'.
Using UUID instead of a simple ID in your Rials application has the following benefits:
If you have decided to use the UUID in your Rails application beware of the following drawbacks:
ModelName.first ModelName.last ModelName.second ModelName.second_to_last
As we have briefly discussed the benefits and drawbacks of using UUID lets jump into How we can set up our Rails application to use UUID instead of regular incremental IDs
To enable UUID in PostgreSQL we need to create a migration
rails g migration enable_uuid_support
Add the following code in the generated migration file
# config/db/migrate/enable_uuid_support.rb class EnableUuidSupport < ActiveRecord::Migration[6.0] def change enable_extension 'pgcrypto' end end
Now set UUID as the default primary key in the generators.rb file as follows
# config/initializers/generators.rb Rails.application.config.generators do |g| g.orm :active_record, primary_key_type: :uuid end
Everything is set, now it’s time to create your first model using UUID.
rails g model user name:string
And tell active record to use UUID as id with the following parameter id: :uuid
# config/db/migrate/create_user.rb class CreateUsers < ActiveRecord::Migration[6.0] def change create_table :users, id: :uuid do |t| t.string :name t.timestamps end end end
NOTE: You also need to set the type as UUID to every reference in your model see the below migration for the article model (article belongs to the user)
rails g model article
Generated migration’s code
# config/db/migrate/create_post_with_uuid.rb class CreateArticle < ActiveRecord::Migration[6.0] def change create_table :users, id: :uuid do |t| t.string :title t.text :body # Note you have to manually specify the type now t.references :user, type: :uuid t.timestamps end end end
That’s all! Happy coding!
Rails is a go-to web framework when you want to create a complex web application. But when it comes to APIs there are many players like Roda, Sinatra, Padrino, Grape and, Rails API.
Stripe is a tool that you can use to handle online payments, but there’s a lot more in it. It is one of the topmost payment methods of the market today.