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 = { |path| File.basename(path, '.rb').camelize.constantize } mongoid_models = { |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 #{}" 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