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.

2
  • you should put your update in the answer below and accept it :) Commented Mar 19, 2013 at 14:05
  • The mongoid link is broken, but this one still exists : mongoid.github.io/old/en/mongoid/docs/rails.html (I was not able to edit the answer, so I put it in a commentary) Commented Oct 28, 2021 at 13:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems that this changed at some point, see docs.mongodb.com/mongoid/current/tutorials/…. Would you be so kind as to revise your answer?
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.