在Rails数据库中显示所有值都为nil的列。

huangapple go评论96阅读模式
英文:

Show columns in Rails DB where every value is nil

问题

  1. 我编写了这个Rake任务来查找Rails应用程序中未使用的列:
  2. ```ruby
  3. desc '列出所有空列'
  4. task list_empty_columns: :environment do
  5. ActiveRecord::Base.connection.tables.each do |table|
  6. # 忽略某些表
  7. next if %w[
  8. action active blazer brands_templates brands_ categories_ components_ covers_ metadata punches schema silos tag
  9. invoice session template_cate
  10. ].any? { |w| table.include?(w) }
  11. # 将类名转换为常量
  12. klass = table.singularize.camelize.constantize
  13. klass.columns.each do |column|
  14. # 检查所有值是否都为空(问题可能出在这里)
  15. next unless klass.where(column.name => nil).all?
  16. p "#{table} #{column.name} 全部为空"
  17. end
  18. end
  19. end

不幸的是,它输出了数据库中也有数据的列。这个任务有什么问题?

  1. <details>
  2. <summary>英文:</summary>
  3. I&#39;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) }

  1. # constantize the class name
  2. klass = table.singularize.camelize.constantize
  3. klass.columns.each do |column|
  4. # check if all values are nil (problem must be here)
  5. next unless klass.where(column.name =&gt; nil).all?
  6. p &quot;#{table} #{column.name} is all nil&quot;
  7. end

end
end

  1. Unfortunately it prints out columns in the DB which have data in them too. What is wrong with the task?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. - 使用 `pluck` 获取所有列值的数组
  6. - 传递一个块来检查 `.all` 是否为 nil 的项
  7. ```ruby
  8. next unless klass.pluck(column.name).all? {|col| col.nil?}

或者使用简写方式

  1. next unless klass.pluck(column.name).all?(&:nil?)
英文:
  • Use pluck to get an array of all column values
  • Pass a block to check if item is nil for .all
  1. next unless klass.pluck(column.name).all? {|col| col.nil?}

or with shorthand

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

huangapple
  • 本文由 发表于 2023年6月22日 07:12:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定