31

I am using Mongoid 3, with Rails 3.2.9 and Unicorn for production. Would like to setup a before_fork & after_fork for the connection to mongodb, found the following code for active record:

before_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info('Disconnected from ActiveRecord')
  end
end

after_fork do |server, worker|
  # Replace with MongoDB or whatever
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
    Rails.logger.info('Connected to ActiveRecord')
  end
end

What is the relevant code for Mongoid (to connect and disconnect)?

Update:

You dont actually need to do this, so for people coming to view this question see:

http://mongoid.org/en/mongoid/docs/rails.html

"Unicorn and Passenger

When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."

Though it would still be interesting to know what would be the equivalent Mongoid code.

ismail
  • 3,882
  • 5
  • 36
  • 47
  • you should put your update in the answer below and accept it :) – gef Mar 19 '13 at 14:05
  • The mongoid link is broken, but this one still exists : https://mongoid.github.io/old/en/mongoid/docs/rails.html (I was not able to edit the answer, so I put it in a commentary) – campisano Oct 28 '21 at 13:21

3 Answers3

19

You dont actually need to do this, so for people coming to view this question see:

http://mongoid.org/en/mongoid/docs/rails.html

"Unicorn and Passenger

When using Unicorn or Passenger, each time a child process is forked when using app preloading or smart spawning, Mongoid will automatically reconnect to the master database. If you are doing this in your application manually you may remove your code."

Though it would still be interesting to know what would be the equivalent Mongoid code.

ismail
  • 3,882
  • 5
  • 36
  • 47
  • It seems that this changed at some point, see https://docs.mongodb.com/mongoid/current/tutorials/mongoid-configuration/#usage-with-forking-servers. Would you be so kind as to revise your answer? – kaikuchn Jan 29 '20 at 09:25
0

What about ::Mongoid.default_session.connect ::Mongoid.default_session.disconnect

JVK
  • 3,782
  • 8
  • 43
  • 67
0

https://docs.mongodb.com/mongoid/current/tutorials/mongoid-configuration/#usage-with-forking-servers

The documentation on mongodb.com says that after_fork and before_fork for unicorn or passenger are required.

This probably changed recently. This is the 7.0 mongoid documentation

Daniel
  • 7,006
  • 7
  • 43
  • 49