2012-11-29 54 views
3

我有一个multitenant Rails应用程序,在许多型号上都有一个tenant_id列。为DelayedJob设置租户范围

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

default_scope { where(tenant_id: Tenant.current_id) } 

Tenant.current_id被设置在应用控制器。

的问题是,当我关于承租人范围的对象(即UserMailer.delay.contact_user(@some_user_in_a_specific_tenant))发送邮件(通过延迟工作),我得到NoMethodError S代表nilClass每当我打电话梅勒内的@some_user_in_a_specific_tenant什么。大概是因为延迟作业过程没有设置Tenant.current_id

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

回答

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) 
+0

我明白了。我的延迟方法所有的邮件程序方法,这使得它更简单,但我会尝试一般方法。 – bevanb

+0

是的,这是唯一合理的方法。 delayed_job进程只是另一个应用程序,拉取数据库记录和运行作业。除非您告诉它,否则无法知道您的主应用程序的状态。 – numbers1311407

+0

看起来很有希望。我会尽力 :) – Dmitri