Search code examples
ruby-on-railspostgresqlmongoidresque

Resque sees mongoid models but not postgresql tables


I'm using mongoid alongside postgresql in a rails 5 app.

My resque jobs work perfectly with the mongoid models, however, when I try to use one of my postgresql tables inside a job, I get the following error:

PG::UndefinedTable: ERROR: relation "admins" does not exist LINE 1: SELECT "admins".* FROM "admins" ^ : SELECT "admins".* FROM "admins"

This is my lib/tasks/resque.rake file

require 'resque/tasks'

task "resque:setup" => :environment do
    ENV['QUEUE'] = '*'
    Resque.before_fork do
    defined?(ActiveRecord::Base) and
      ActiveRecord::Base.connection.disconnect!
  end

  Resque.after_fork do
    defined?(ActiveRecord::Base) and
      ActiveRecord::Base.establish_connection
  end
end

The mentioned postgres table does exist, and works perfectly with the rails app. It seems like, at least outside of the main rails app, ActiveRecord defaults to using mongoid, so none of my postgresql models are visible inside the worker. Or maybe not.

Am I missing something?


Solution

  • I ended up fixing it by tweaking my Procfile and task file a bit, the issue was due to resque not picking up the right environment (hence the undefined model relationships)

    Procfile:

    web: bundle exec puma -t 5:5 -p ${PORT:-3000} -e ${RACK_ENV:-development}
    worker: bundle exec rake resque:pool
    

    I ended up using lib/tasks/resque.rake just to declare tasks, and moved the initialisation code to lib/tasks/resque-pool.rake. Basically resque:setup gets called before resque:pool:setup, to it preloads the rails environment for the pool manager.

    require 'resque/tasks'
    require 'resque/pool/tasks'
    
    task "resque:setup" => :environment do
        Resque.before_fork = Proc.new do
            ActiveRecord::Base.connection.disconnect!
        end
        Resque.after_fork = Proc.new do
            ActiveRecord::Base.establish_connection
        end
    end
    
    task "resque:pool:setup" do
    
    end