ruby-on-railsrubyrake-task

Show columns in Rails DB where every value is nil


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?


Solution

  • next unless klass.pluck(column.name).all? {|col| col.nil?}
    

    or with shorthand

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