Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting tenant scope for DelayedJob

I have a multitenant Rails app that has a tenant_id column on many models.

Each model that belongs to a specific tenant has a default scope based on a class variable on the Tenant class:

default_scope { where(tenant_id: Tenant.current_id) }

Tenant.current_id is set in the application controller.

The problem is that when I send mail (via a Delayed Job) regarding a tenant-scoped object (ie. UserMailer.delay.contact_user(@some_user_in_a_specific_tenant)), I get NoMethodErrors for nilClass whenever I call anything on @some_user_in_a_specific_tenant within the Mailer. Presumably because the Delayed Job process isn't setting the Tenant.current_id.

How can I get DJ to access the objects I'm passing in?

like image 260
bevanb Avatar asked Feb 01 '26 09:02

bevanb


1 Answers

Grab the current_id when you queue the job and build a scope out of that that doesn't depend on a class variable from the app. Or get a list of record ids to operate on first, passing that to DJ.

Examples:

def method_one(id)
  Whatever.where(:tenant_id => id).do_stuff
end

def method_two(ids)
  Whatever.find(ids).do_stuff
end

handle_asynchronously :method_one, :method_two

# then
method_one(Tenant.current_id)

# or
ids = Whatever.all.map(&:id)
method_two(ids)
like image 54
numbers1311407 Avatar answered Feb 03 '26 01:02

numbers1311407