Skip to content

Instantly share code, notes, and snippets.

@xhoy
Created September 10, 2013 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xhoy/6510171 to your computer and use it in GitHub Desktop.
Save xhoy/6510171 to your computer and use it in GitHub Desktop.
validate models vs db in an rails app
# file: validate_models.rake
# task: rake db:validate_models
namespace :db do
desc "Run model validations on all model records in database"
task :validate_models => :environment do
puts "-- records - model --"
Dir.glob(Rails.root.join('app/models/**/*.rb')).each { |file| require file }
ActiveRecord::Base.descendants.select { |c|
c.base_class == c}.sort_by(&:name).each do |klass|
total = klass.count
printf "%10d - %s\n", total, klass.name
chunk_size = 1000
(total / chunk_size + 1).times do |i|
chunk = klass.find(:all, :offset => (i * chunk_size), :limit => chunk_size)
chunk.reject(&:valid?).each do |record|
puts "#{record.class}: id=#{record.id}"
p record.errors.full_messages
puts
end rescue nil
end
end
end
end
@amiel
Copy link

amiel commented Sep 10, 2013

You might be interested in .find_each.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment