railties

Mongoid provides some railties and initializers that one should be aware of when writing a Rails application with Mongoid.

configuration

You can set Mongoid configuration options in your application.rb along with other Rails environment specific options by accessing config.mongoid. Options set here will override those set in your config/mongoid.yml.

module MyApplication
  class Application < Rails::Application
    config.mongoid.logger = Logger.new($stdout, :warn)
    config.mongoid.persist_in_safe_mode = true
  end
end

model preloading

In order to properly set up single collection inheritance, Mongoid needs to preload all models before every request in development mode. This can get slow, so if you are not using any inheritance it is recommended you turn this feature off.

config.mongoid.preload_models = false

exceptions

Similar to Active Record, Mongoid tells raise to return specific http codes when some errors are raised.

  • Mongoid::Errors::DocumentNotFound: 404
  • Mongoid::Errors::Validations: 422

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.