2009-01-31 63 views
15

我有一个Mail模型下面的模式分组:计数,并在同一时间

t.string "mail" 
t.integer "country" 
t.boolean "validated" 
t.datetime "created_at" 
t.datetime "updated_at" 

而且我想找到的前5个国家的数据库,所以我继续前进,键入

@top5 = Mail.find(:all,:group => 'country',:conditions => [ "validated = ?" , "t" ], :limit => 5) 

这会告诉我的组(我需要一个ORDER BY我不知道怎么写)

@top5 = Mail.count(:all,:group => 'country',:conditions => [ "validated = ?" , "t" ], :limit => 5) 

这会告诉我有多少邮件每组

林,如果我能集团想在和计算只是一个去

回答

19
 
Mail.find(
    :all, 
    :select => 'count(*) count, country', 
    :group => 'country', 
    :conditions => ['validated = ?', 't' ], 
    :order => 'count DESC', 
    :limit => 5) 

这应该给你,有一个国家属性和计数属性记录。

+0

真正应该用来代替 'T' – Swards 2010-12-20 19:04:53

+1

@airportyh Rails的API说,ActiveRecord的。find已被弃用(http://apidock.com/rails/ActiveRecord/Base/find/class)。你知道在Rails 3上做到这一点的最佳方式吗? – dcarneiro 2012-01-30 18:06:12

24

尝试:

Mail.count(:group => 'country', :conditions => ['validated = ?', 't'])

我不知道算接受:limit虽然。

编辑:

我认为这是更具可读性:

Mail.count(:group => :country, :conditions => {:validated => true})

22

使用Rails 3,您可以进一步简化它:

Mail.where(validated: true).count(group: :country) 

您可以在字段排序该组 - 在这种情况下只:国家将是有效的:

Mail.where(validated: true) 
    .order(:country) 
    .count(group: :country) 

您还可以通过计数顺序,当使用“count_all”:

Mail.where(validated: true) 
    .order("count_all desc") 
    .count(group: :country) 

您也可以限制返回组的数量。要做到这一点,你必须在调用计数之前调用限制(因为#count回报ActiveSupport::OrderedHash):

Mail.where(validated: true) 
    .order("count_all desc") 
    .limit(5) 
    .count(group: :country) 

为Rails 4更新语法:

Mail.where(validated: true) 
    .group(:country) 
    .count 
0

我也只好组数据与城市名称并显示计数每个城市有多少排有特定条件。所以这是我如何做:

CityData.where(:status => 1).group(:city_name).count 

的这个输出是:

{:Mumbai => 10, :Dublin => 7, :SF => 9}