使用Rails获取特定表的所有表名和行数?

问题描述:

如何从特定数据库中获取特定表的所有表名和行数?使用Rails获取特定表的所有表名和行数?

结果

Table Name , Row Count , Table Size(MB) 
--------------------------------------- 

table_1 , 10  , 2.45 

table_2 , 20  , 4.00 

@temp_table = [] 
    ActiveRecord::Base.connection.tables.each do |table| 
     count = ActiveRecord::Base.connection.execute("SELECT COUNT(*) as count FROM #{table}").fetch_hash['count'] 
     size = ActiveRecord::Base.connection.execute("SHOW TABLE STATUS LIKE '#{table}'").fetch_hash 
     @temp_table << {:table_name => table, 
      :records => count.to_i, 
      :size_of_table => ((BigDecimal(size['Data_length']) + BigDecimal(size['Index_length']))/1024/1024).round(2) 
     } 
     end 
    end 

ActiveRecord::Base.connection.tables.each do |table|  
h = ActiveRecord::Base.connection.execute("SHOW TABLE STATUS LIKE '#{table}'").fetch_hash 
puts "#{h['Name']} has #{h['Rows']} rows with size: #{h['Data_length']}" 
end 
+0

我怎么能取表的大小? – 2011-04-01 04:59:28

+0

更新了您的更新的答案。 – 2011-04-01 05:09:45

+0

使用InnoDB显示表格状态不会返回精确的表格行。 – 2011-04-01 05:25:30