Search code examples
ruby-on-railsrubyherokuunicorn

Rails/Unicorn before_fork block, disconnect from secondary database


We're using two databases, one main, and one secondary in a seperate model, like so:

class SecondModel < ActiveRecord::Base
  establish_connection(ENV['SECOND_DATABASE'])
end

I'm going to switch to Unicorn on a Heroku app, and we have to disconnect the database here:

before_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
  end
end

I am not sure about closing the connection for the second database. Does anybody have any thoughts on this?


Solution

  • Ok I think I got it working now, here is the code:

    before_fork do |server, worker|
      if defined?(ActiveRecord::Base)
        # disconnect primary database
        ActiveRecord::Base.connection.disconnect!
        Rails.logger.info('Disconnected from ActiveRecord')
    
        # disconnect the second database
        SecondModel.connection.disconnect! if SecondModel.connection.active?
        Rails.logger.info('Disconnected from SecondModel')
      end
    end
    
    after_fork do |server, worker|
      if defined?(ActiveRecord::Base)
        # connect primary database
        ActiveRecord::Base.establish_connection
        Rails.logger.info('Connected to ActiveRecord')
    
        # connect second database
        SecondModel.establish_connection(ENV["SECOND_DATABASE"])
        Rails.logger.info('Connected to SecondModel')
    
        # verify connections
        ActiveRecord::Base.verify_active_connections!
      end
    end
    

    I've got some errors because I was verifying the connections before re-connection to the SecondModel's database.

    Any thoughts are welcome!