Validate all your records in one fell swoop


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # file: validate_models.rake
  2. # task: rake db:validate_models
  3. namespace :db do
  4. desc "Run model validations on all model records in database"
  5. task :validate_models => :environment do
  6. puts "-- records - model --"
  7. Dir.glob(RAILS_ROOT + '/app/models/**/*.rb').each { |file| require file }
  8. Object.subclasses_of(ActiveRecord::Base).select { |c|
  9. c.base_class == c}.sort_by(&:name).each do |klass|
  10. total = klass.count
  11. printf "%10d - %s\n", total, klass.name
  12. chunk_size = 1000
  13. (total / chunk_size + 1).times do |i|
  14. chunk = klass.find(:all, :offset => (i * chunk_size), :limit => chunk_size)
  15. chunk.reject(&:valid?).each do |record|
  16. puts "#{record.class}: id=#{record.id}"
  17. p record.errors.full_messages
  18. puts
  19. end rescue nil
  20. end
  21. end
  22. end
  23. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.