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

大兔子大兔子 提交于 2019-12-05 22:43:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6479039/how-can-i-force-delayed-job-to-use-a-specific-db-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!