Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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