I recently learned about Global IDs in Rails applications.
Just as a reference, the link to the Global ID repo is https://github.com/rails/globalid.
That GitHub repo does a good job of explaining what Global ID is but TLDR version is that it’s a global identifier that you can use to locate an instance of a model.
I found it to be pretty useful when passing in ids of various model instances in a job queue. For example, let’s say that you have a few models with one model having a belongs_to
polymorphic association with the rest of the models. You create a record of this polymorphic model in a job class. Let’s have an example here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class User < ApplicationRecord has_many :pictures, as: :imageable end class Dog < ApplicationRecord has_many :pictures, as: :imageable end class Picture < ApplicationRecord belongs_to :imageable, polymorphic: true end class PictureCreatorJob @queue = :picture_generation def self.perform(owner_global_id) owner = GlobalID::Locator.locate(owner_global_id) Picture.create!(imageable: owner) end end user = User.find(params[:user_id]) PictureCreatorJob.perform(user.to_global_id) |
In the PictureCreatorJob
, thanks to us using the global_id
of the user, we can locate the model without having to conditionally check which model we should be querying with ActiveRecord. I find that in these specific situations, Global ID can make your code more succinct and concise.