Spec for has_many with dependent option

posted by alexis reigel on february 15, 2016

New post on the Panter Blog (the company I’m working for):

blog.panter.ch/2016/01/12/spec-for-has_many-with-dependent-option.html

Idempotent seeds in rails

posted by alexis reigel on august 28, 2015

Guest post on the Panter Blog (the company I’m working for):

blog.panter.ch/2015/08/05/idempotent-seeds-in-rails.html

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

      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

And here’s the whole thing as a gist.