Indexes and Rails

64 views
Skip to first unread message

John Nunemaker

unread,
Oct 29, 2009, 3:03:07 PM10/29/09
to mongo...@googlegroups.com
So I just confirmed that MongoMapper.ensure_indexes! effectively does
nothing with Rails. The reason is that the models are autoloaded or
something (if someone knows details do tell).

I worked around this by loading constantizing each model and then
calling ensure_indexes! after the fact. Below is my entire mongo.rb
initializer (with rails 2.3.4).

# connect to mongo
MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017, {
:auto_reconnect => true,
:logger => Rails.logger
})

# setup default MM database
MongoMapper.database = "harmony-#{Rails.env}"

# make sure each model is loaded and thus indexes are collected
Dir[Rails.root + 'app/models/**/*.rb'].each do |model_path|
File.basename(model_path, '.rb').classify.constantize
end

# ensure all needed indexes are created
MongoMapper.ensure_indexes!

# handle passenger forking
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.database.connect_to_master if forked
end
end

This seems to get the trick done for me and I confirmed that the
indexes were created and such. If anyone knows a better way to get
around this, please let me know as this feels insanely dirty. Thanks.

Regards,
John Nunemaker

Sam

unread,
Oct 29, 2009, 8:20:35 PM10/29/09
to MongoMapper
Is there a reason that indexes can't be created on the fly, i.e. when
a query is first made?

I assume that the ensure_indexes! call is very cheap if the indexes
have already been created (please confirm). And if they haven't, the
delay would probably be acceptable in most circumstances IMHO.

I don't think your approach will scale nicely if models are defined in
other locations (lib, etc.) or in plugins.

BTW, ActiveSupport::Dependencies is what causes the model autoloading
in Rails. It hooks into require and load and looks in the dependency
load path to find and load the missing constant.

-Sam

Adam Greene

unread,
Nov 17, 2009, 11:13:51 PM11/17/09
to MongoMapper
+1 to sam's idea. Right now, within my document I just call
'ensure_index!' and that does the trick (though it is inefficient as
it will call all model's indexes; I can get away with it because I
only have 2)

Adam
Reply all
Reply to author
Forward
0 new messages