2012-12-03 263 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:啊,我明白了。看看我更新的答案的底部。 –

相關問題