英文:
Show columns in Rails DB where every value is nil
问题
我编写了这个Rake任务来查找Rails应用程序中未使用的列:
```ruby
desc '列出所有空列'
task list_empty_columns: :environment do
ActiveRecord::Base.connection.tables.each do |table|
# 忽略某些表
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) }
# 将类名转换为常量
klass = table.singularize.camelize.constantize
klass.columns.each do |column|
# 检查所有值是否都为空(问题可能出在这里)
next unless klass.where(column.name => nil).all?
p "#{table} #{column.name} 全部为空"
end
end
end
不幸的是,它输出了数据库中也有数据的列。这个任务有什么问题?
<details>
<summary>英文:</summary>
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?
</details>
# 答案1
**得分**: 1
- 使用 `pluck` 获取所有列值的数组
- 传递一个块来检查 `.all` 是否为 nil 的项
```ruby
next unless klass.pluck(column.name).all? {|col| col.nil?}
或者使用简写方式
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
next unless klass.pluck(column.name).all? {|col| col.nil?}
or with shorthand
next unless klass.pluck(column.name).all?(&:nil?)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论