Mongoid clean indexes

5 Jul 2012

Do you know, when you create indexes, Mongoid doesn't remove undefined indexes?

That is annoying and causes me a problem.

So, here is the rake task for removing all indexes and recreating only the ones that are defined:

namespace :db do desc "Remove all indexes and create only the ones defined" task :reindex => :environment do all_files = Dir.glob(Rails.root.join('app', 'models', '*.rb')) all_models = all_files.map { |path| File.basename(path, '.rb').camelize.constantize } mongoid_models = all_models.select { |m| m.respond_to?(:create_indexes) } mongoid_models.each do |model| begin model.collection.drop_indexes rescue Exception end begin model.create_indexes rescue Exception=>e puts "Error while indexing #{model.name}" raise e end end end end

You can put this code into `lib/tasks/mongoid.rake`.

And when you want to clean indexes, just type `rake db:reindex`

Give it a kudos