1 min read

Global IDs in Rails

Global IDs in Rails

Global ID is a feature within Rails that lets you query for a record without having to specify the model/table you're querying against.

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.

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.