2011-11-07 34 views
0

在我的控制,我有:Rails如何計算非空白的列?

def sedomain 
country_codes = %w[ dk se com net org info ] 
@domains = { } 
country_codes.each do |cc| 
    @domains[cc.to_sym] = { :navn => ".#{cc}" } 
    end 
render :layout => 'page' 
end 

DK本身融爲一體網組織的信息都在我的域表中的列。

我要統計有多少是沒有空白的

我已經試過這樣的事情:

def sedomain 
country_codes = %w[ dk se com net org info ] 
@domains = { } 
country_codes.each do |cc| 
    @domains[cc.to_sym] = { :navn => ".#{cc}", :count => Domain.#{cc}.count } 
    end 
render :layout => 'page' 
end 

但我得到一個nomethod錯誤。

+0

它是:計數=>域#{CC} .Count之間或:。計數=>域 「#{CC}」 計數? –

+0

它是域名。#{cc} .count –

+0

#表示評論。作爲tadman的答案它將是:count => Domain.send(cc).count –

回答

2
Domain.count(cc) 

Domain.count(cc, :conditions => ["`#{cc}` IN NOT NULL OR `#{cc}` != ''"]) 
+0

這工作正常。它比Domain.where(:「#{cc.gsub('。',''))」。not_eq => nil).count更好嗎? –

7

你真的需要得到一本關於Ruby的書,因爲這很簡單。 #{...}是一個插值器,僅用於字符串和字符串。在特定上下文之外,#通常被解釋爲註釋,並將該行的其餘部分呈現爲無效。正確的語法高亮編輯器會揭示這一點,即使StackOverflow的代碼高亮顯示器也是這樣工作的。

你需要的是send,如Domain.send(cc).count

+0

我得到一個沒有方法錯誤:未定義的方法'dk'for #<類別:0x753c258>。我確實想到使用:count => Domain.where(:「#{cc.gsub('。','')}」。not_eq => nil).count哪些工作。 –

+0

在大多數情況下使用'send'是一個Contrived Complexity codesmell。 – Eric

+0

這是一個功能性的解決方案,經過適當的審查後,它的工作效果很好,但它應該是您在清理實施時重構的第一件事情之一。將其封裝在一個可在單個可測試接口中處理驗證和委派的方法是一種優越的解決方案。在這種情況下,它是對'#{...}'所打算的內容的直接翻譯。 – tadman