Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force delayed_job to use a specific db connection?

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

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

Any idea how can I do this?

like image 743
JAG Avatar asked Jun 25 '11 16:06

JAG


1 Answers

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.

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

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.

like image 60
skorks Avatar answered Oct 23 '22 01:10

skorks