Skip to content

Instantly share code, notes, and snippets.

@adamrobbie
Created August 29, 2012 13:14
Show Gist options
  • Save adamrobbie/3512290 to your computer and use it in GitHub Desktop.
Save adamrobbie/3512290 to your computer and use it in GitHub Desktop.
Rake task to handle orphaned records
namespace :db do
desc "Handle orphans"
task :handle_orphans => :environment do
Dir[Rails.root + "app/models/**/*.rb"].each do |path|
require path
end
ActiveRecord::Base.send(:descendants).each do |model|
model.reflections.each do |association_name, reflection|
if reflection.macro == :belongs_to
model.all.each do |model_instance|
unless model_instance.send(reflection.primary_key_name).blank?
if model_instance.send(association_name).nil?
print "#{model.name} with id #{model_instance.id} has an invalid reference, would you like to handle it? [y/n]: "
case STDIN.gets.strip
when "y", "Y"
# handle it
end
end
end
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment