如何强制delay_job使用特定的数据库连接? [英] How can I force delayed_job to use a specific db connection?

查看:83
本文介绍了如何强制delay_job使用特定的数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails 3应用程序,该应用程序根据子域使用不同的数据库。我通过在ApplicationController中使用建立连接来完成此操作。

I have a Rails 3 applications that uses different databases depending on the subdomain. I do this by using "establish_connection" in the ApplicationController.

现在,我正在尝试使用delay_job gem进行一些后台处理,但是它使用的是数据库连接在那一刻活跃。它正在连接到子域数据库。

Now I'm trying to use delayed_job gem to do some background processing, however it uses the database connection that it's active in that moment. It's connecting to the subdomain database.

我想强迫它使用公共数据库。对于某些在模型中称为建立连接的模型,我已经这样做:

I'd like to force it to use the "common" database. I've done this for some models calling "establish_connection" in the model like this:

class Customer < ActiveRecord::Base
  establish_connection ActiveRecord::Base.configurations["#{Rails.env}"]
  ...
end

任何想法我该怎么做?

推荐答案

此处这是您需要知道的。在您的应用程序中包含DelayedJob gem时,您会为其创建迁移以创建存储作业的表,但是您没有创建模型。这是因为DelayedJob已在gem中包含一个模型(即 Delayed :: Job )。您需要做的是对该模型进行少许修补,就像您对自己的模型所做的一样。您可以在初始化程序中执行此操作。

Here is what you need to know. When you include the DelayedJob gem in your app you create a migration for it to create the table where the jobs are stored, but you don't create a model. This is because DelayedJob already has a model included in the gem (i.e. Delayed::Job). What you need to do is patch this model slightly, just like you did with your own models. You can do this in an initializer.

您可能已经拥有一个用于配置DelayedJob的初始化程序,如果可以的话,可以在其中进行此操作,如果不需要,则可以创建一个。因此,如果没有,请创建您的初始化程序(在 config / initializers 中),我们将其称为 delayed_job_config.rb ,现在向其中添加以下内容:

You may already have an initializer to configure DelayedJob, if so you can do this in there, if not you need to create one. So, create your initializer (in config/initializers) if you don't have one, we'll call it delayed_job_config.rb, now add the following to it:

Delayed::Job.class_eval do
  establish_connection ActiveRecord::Base.configurations["#{Rails.env}"]
end

对DelayedJob模型所做的操作与对自己的模型所做的操作相同。现在,DelayedJob将使用该连接将作业放入数据库中。

We've done to the DelayedJob model the same thing you did to your own models. Now DelayedJob will use that connection to put jobs in the DB.

这篇关于如何强制delay_job使用特定的数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆