Ruby on rails 如何计算每个记录在Rails中输入了多少数据库字段

Ruby on rails 如何计算每个记录在Rails中输入了多少数据库字段,ruby-on-rails,attributes,Ruby On Rails,Attributes,我试图检索数据库完整性的简单统计数据。考虑到未输入的字段中有“null”或“null”,我想知道每个记录中已填写的字段总数中有多少个字段 以下是现有代码的外观: <% if @products %> <% total_attribute_count = Product.columns.size %> <% @products do |product| -%> <p><%= platform.name %></p

我试图检索数据库完整性的简单统计数据。考虑到未输入的字段中有“null”或“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 %>

我想在这里填写一些属性,这样我可以根据总属性计数计算百分比

您可以尝试以下操作

#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)
参考号