为DelayedJob设置租户范围

时间:2012-11-29 04:33:49

标签: ruby-on-rails delayed-job multi-tenant

我有一个多租户Rails应用,在许多型号上都有tenant_id列。

属于特定租户的每个模型都有一个基于Tenant类的类变量的默认范围:

default_scope { where(tenant_id: Tenant.current_id) }

Tenant.current_id在应用程序控制器中设置。

问题在于,当我发送关于租户范围对象(即UserMailer.delay.contact_user(@some_user_in_a_specific_tenant))的邮件(通过延迟工作)时,每当我打电话时,NoMethodError都会收到nilClass秒梅勒内@some_user_in_a_specific_tenant上的任何内容。大概是因为延迟作业流程没有设置Tenant.current_id

如何让DJ访问我传入的对象?

1 个答案:

答案 0 :(得分:1)

在对作业进行排队时获取current_id,并构建一个不依赖于应用程序中的类变量的作用域。或者先获取一份记录ID列表,然后将其传递给DJ。

示例:

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)