2012-12-03 241 views
1

我是一个新手,我需要执行一些sql查询和数组输出到视图。Array of ActiveRecord :: Base.connection.execute Ruby on Rails

上命令

Account Load (36.0ms) SELECT "public"."accounts".* FROM "public"."accounts" 
    Account Load (2.0ms) SELECT subdomain FROM "public"."accounts" 
    (88.0ms) select pg_size_pretty(CAST((SELECT SUM(pg_total_relation_size(table 
_schema || '.' || table_name)) FROM information_schema.tables WHERE table_schem 
a = 'subdomain1 subdomain2') As bigint)) As schema_size 
    Rendered accounts/kapasitas.html.erb within layouts/admin (239.0ms) 
Completed 200 OK in 2765ms (Views: 2208.1ms | ActiveRecord: 484.0ms) 

conttroler

@accounts = Account.all 
@itemlist = Account.find(:all,:select => 'subdomain') 

@schemasize = ActiveRecord::Base.connection.select_rows(%q{select pg_size_pretty(CAST((SELECT SUM(pg_total_relation_size(table_schema || '.' || table_name)) FROM information_schema.tables WHERE table_schema = '}[email protected](&:subdomain).join(" ")+%q{') As bigint)) As schema_size}).to_s.gsub(/\D/, '').to_f/1024 

输出上html.erb上视图

<tr> 
    <td><%= account.subdomain %></td> 
    <td><%= @schemasize %></td> 
    </tr> 

输出:http://i.cubeupload.com/jVrShN.png

不能为每个子域的大小模式。

我想输出,如:http://i.cubeupload.com/PMPBYn.png

我怎么能这样做? 有什么想法?

回答

2

首先,不要打扰pg_size_pretty,让显示代码担心格式化。

接下来,您需要明白select_rows返回一个数组数组(每个返回的行都有一个内部数组),并且数组条目将是字符串。

您的查询返回一行,因此您可以使用first提取该行,并使用另一个first从该行提取单列。然后你可以使用to_i得到一个数字,该助手就明白了:

@schemasize = ActiveRecord::Base.connection.select_rows(%q{select CAST(...)}) 
              .first 
              .first 
              .to_i 

和显示时,用number_to_human_size

<%= number_to_human_size(@schemasize) %> 

参见文档为number_to_human_size可能的选项列表。

如果您担心to_i呼叫溢出Fixnum,请勿。 to_i将切换到使用需要Bignum

1.9.2p312 :011 > '1'.to_i.class 
=> Fixnum 
1.9.2p312 :012 > '12345678910111213141516'.to_i.class 
=> Bignum 

number_to_human_size是一样高兴Bignum,因为它是与Fixnum

如果你总是希望以MB为单位的结果,然后由专人使用(BigDecimalto_dto_f代替to_i,规模化的东西(如你现在做的),并使用String#%对其进行格式化:

<%= '%.4f' % @schemasize %> 

如果你想对每个方案的尺寸,那么你要调整你的table_schema = ...table_schema in (...),然后在一个GROUP BY table_schema钉。事情是这样的:

select table_schema, sum(pg_total_relation_size(table_schema || '.' || table_name)) 
from information_schema.tables 
where table_schema in ('subdomain1', 'subdomain2') 
group by table_schema 

这会给你数组像这样从select_rows数组:

[ 
    [ 'subdomain1', '3284762389' ], 
    [ 'subdomain2', '129837' ] 
] 

,然后你可以解开它的每一行:

@sizes = raw.map { |schema, size| [ schema, size.to_i ] } 
# Or to_d as noted above 

然后你可以在ERB中循环使用@sizes,并按上述格式设置大小。

+0

thx bro,但这不是我的意思,我希望我的查询把架构大小**每个子域** ..如何从我的查询中获取数组。 – GeekToL

+0

@KapanjadiMomod:啊,我明白了。看看我更新的答案的底部。 –

相关问题