Skip to content

Instantly share code, notes, and snippets.

@koffeinfrei
Last active August 29, 2015 13:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koffeinfrei/8931935 to your computer and use it in GitHub Desktop.
Save koffeinfrei/8931935 to your computer and use it in GitHub Desktop.
rails rake task for checking validity of all rails model entries

Put this file in your rails project at lib/tasks/db.rake. Use it like

$ rake db:data:validate
namespace :db do
namespace :data do
desc 'Validates all records in the database'
task :validate => :environment do
original_log_level = ActiveRecord::Base.logger.level
ActiveRecord::Base.logger.level = 1
puts 'Validate database (this will take some time)...'
Dir["#{Rails.root}/app/models/**/*.rb"].each { |f| require "#{ f }" }
ActiveRecord::Base.subclasses.
reject { |type| type.to_s.include? '::' }. # subclassed classes are not our own models
each do |type|
begin
type.find_each do |record|
unless record.valid?
puts "#<#{ type } id: #{ record.id }, errors: #{ record.errors.full_messages }>"
end
end
rescue Exception => e
puts "An exception occurred: #{ e.message }"
end
end
ActiveRecord::Base.logger.level = original_log_level
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment