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

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

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&#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) }

# 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 =&gt; nil).all?

  p &quot;#{table} #{column.name} is all nil&quot;
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?(&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:

确定