This is an archived copy of my old blog (2022 to 2023). Go to the current page
Mateus Nava

Mateus Nava

January 16, 2022

Rails Global ID

By Kyle Glenn (unsplash.com)
By Kyle Glenn (unsplash.com)
A Global ID is an identification that uniquely identifies a model instance, very simple to understand. For example (Link is the model):
Link.find(1).to_global_id.to_s # gid://link-share/Link/1

You can find a record by Global ID only:
GlobalID::Locator.locate('gid://link-share/Link/1') # Returns the link id 1 instance

If you need to secure your global id, you can use the Signed Global ID:
Link.find(1).to_signed_global_id.to_s # BAh7CEkiCGdpZAY6BkVUSSIcZ2lkOi8vbGluay1zaGFyZS9MaW5rLzEGOwBUSSIMcHVycG9zZQY7AFRJIgxkZWZhdWx0BjsAVEkiD2V4cGlyZXNfYXQGOwBUSSIdMjAyMi0wMi0xNlQyMzo1MDo0MC41NjdaBjsAVA==--c4ac4815a3022eebf161ea0be38c6674c4110f7b

To find by Signed Global ID
GlobalID::Locator.locate_signed('BAh7CEkiCGdpZAY6BkVUSSIcZ2lkOi8vbGluay1zaGFyZS9MaW5rLzEGOwBUSSIMcHVycG9zZQY7AFRJIgxkZWZhdWx0Bj
sAVEkiD2V4cGlyZXNfYXQGOwBUSSIdMjAyMi0wMi0xNlQyMzo1MDo0MC41NjdaBjsAVA==--c4ac4815a3022eebf161ea0be38c6674c4110f7b') # Returns the link id 1 instance

Using the global id you can find any model by a simple string (the global id), without even knowing the model's class, very useful in many situations.

References