Skip to content

Instantly share code, notes, and snippets.

@schpet
Created February 18, 2016 19:35
Show Gist options
  • Save schpet/892aef0f7700388f8446 to your computer and use it in GitHub Desktop.
Save schpet/892aef0f7700388f8446 to your computer and use it in GitHub Desktop.
Find all invalid ActiveRecord records
namespace "invalid_records" do
desc "Find all invalid records"
task find_all: :environment do
Rails.application.eager_load!
i = 0
invalid_records = ActiveRecord::Base.subclasses.map do |active_record_class|
begin
next if active_record_class&.abstract_class == true
ids = active_record_class.unscoped.pluck(:id)
invalid_record_ids = ids.select do |id|
i += 1
begin
next !active_record_class.unscoped.find(id).valid?
rescue
next true
end
end
[active_record_class.to_s, invalid_record_ids]
rescue ActiveRecord::StatementInvalid
puts "#{active_record_class} doesn't have an id column, skipping"
next
rescue
puts "?" * 90
puts "couldn't handle #{active_record_class}"
next
end
end.compact.to_h
relevant_invalid_records = invalid_records.select { |klass, record_ids| record_ids.present? }
if relevant_invalid_records.present?
invalid_records_msg = relevant_invalid_records.map do |klass, record_ids|
"#{klass} (#{record_ids.length}):\n#{record_ids.join("\n")}"
end.join("\n\n")
fail "Searched through #{i} records, the following records are invalid:\n\n#{invalid_records_msg}\n"
else
puts "Searched through #{i} records, no invalid records were found"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment