我正在尝试检索数据库完整性的简单统计信息。我想知道每条记录中填写的字段总数中有多少字段,考虑到未输入的字段中包含“null”或“”。
以下是现有代码的外观:
<% if @products %>
<% total_attribute_count = Product.columns.size %>
<% @products do |product| -%>
<p><%= platform.name %></p>
<p>I would like to have here a number of attributes filled in, so I could calculate a percentage based on total_attribute_count</p>
<% end -%>
<% end %>
答案 0 :(得分:2)
您可以尝试以下
#Following line will gives you total number of columns in the table
a = Product.column_names.length
#Following line will gives you total number of columns which are filled
b = Product.column_names.map{|a| product.send(a)}.compact.length
#Following line gives you total number of columns which are nil or null
a - b
To calculate % you can do following
(b.to_f*100/a.to_f)