Created
August 29, 2012 13:14
-
-
Save adamrobbie/3512290 to your computer and use it in GitHub Desktop.
Rake task to handle orphaned records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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