Show columns in Rails DB where every value is nil

64 views Asked by At

I've written this rake task to find unused columns in a Rails app:

desc 'list all nil columns'
task list_empty_columns: :environment do
  ActiveRecord::Base.connection.tables.each do |table|
    # ignore some tables
    next if %w[
      action active blazer brands_templates brands_ categories_ components_ covers_ metadata punches schema silos tag
      invoice session template_cate
    ].any? { |w| table.include?(w) }

    # constantize the class name
    klass = table.singularize.camelize.constantize
    klass.columns.each do |column|
      # check if all values are nil (problem must be here)
      next unless klass.where(column.name => nil).all?

      p "#{table} #{column.name} is all nil"
    end
  end
end

Unfortunately it prints out columns in the DB which have data in them too. What is wrong with the task?

1

There are 1 answers

2
Arty.Simon On BEST ANSWER
  • Use pluck to get an array of all column values
  • Pass a block to check if item is nil for .all
next unless klass.pluck(column.name).all? {|col| col.nil?}

or with shorthand

next unless klass.pluck(column.name).all?(&:nil?)