validate all database records rails task

posted by alexis reigel on march 25, 2014

Sometimes you need to validate all your active record entries in the database. This may happen when you update validations in your models and you want to check which models need an update. Or you have a legacy system that has invalid records. Or some other system wrote to the database (without the rails application’s validation).

Here’s a rake task that validates all database rows for all the ActiveRecord models in your rails application.

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 }" }

        reject { |type| type.to_s.include? '::' }. # subclassed classes are not our own models
        each do |type|
            type.find_each do |record|
              unless record.valid?
                puts "#<#{ type } id: #{ }, errors: #{ record.errors.full_messages }>"
          rescue Exception => e
            puts "An exception occurred: #{ e.message }"

      ActiveRecord::Base.logger.level = original_log_level

And here’s the whole thing as a gist.

commented by Shero on december 22, 2015

= session['user'].friends #make sure the friendship is not self-friendship if @session['user'].id == @params['friend_id'] flash[:notice] = 'You are aldraey your own friend!' redirect_to :controller => 'user', :action => 'welcome' #and make sure there isn't aldraey a friendship elsif @friends.find(:first, :conditions => [ "friend_id = ?",params[“friend_id”].to_i]) flash[:notice] = ‘You are aldraey friends!’ redirect_to :controller => ‘user’, :action => ‘welcome’ else newFriend = User.find(params[c3a2e282ace284a2friend_idc3a2e282ace284a2]) @friends << newFriend flash[:notice] = c3a2e282accb9cAdded friend!c3a2e282ace284a2 redirect_to :controller => c3a2e282accb9cuserc3a2e282ace284a2, :action => c3a2e282accb9clistc3a2e282ace284a2 end endAlthough I am getting an application error on the first line.friends = @session[‘user’].friendsHow are you meant to access the array?Many thanks,Jason