同时计数和分组

DFe*_*oso 15 ruby-on-rails

我有一个Mail具有以下架构的模型:

t.string   "mail"
t.integer  "country"
t.boolean  "validated"
t.datetime "created_at"
t.datetime "updated_at"
Run Code Online (Sandbox Code Playgroud)

我想找到数据库中的前5个国家,所以我继续输入

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

这将告诉我团体(我需要一个订单,我不知道怎么写)

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

这将告诉我每组中有多少邮件

我想知道我是否可以一次性分组和计算

Can*_*der 24

尝试:

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

我不确定算是否接受:limit了.

编辑:

我认为这更具可读性:

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


tee*_*tee 22

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

Mail.where(validated: true).count(group: :country)
Run Code Online (Sandbox Code Playgroud)

您可以按组中的字段排序 - 仅在这种情况下:国家/地区有效:

Mail.where(validated: true)
    .order(:country)
    .count(group: :country)
Run Code Online (Sandbox Code Playgroud)

您也可以使用"count_all"按计数订购:

Mail.where(validated: true)
    .order("count_all desc")
    .count(group: :country)
Run Code Online (Sandbox Code Playgroud)

您还可以限制返回的组数.为此,您必须在调用count之前调用limit(因为#count返回ActiveSupport::OrderedHash):

Mail.where(validated: true)
    .order("count_all desc")
    .limit(5)
    .count(group: :country)
Run Code Online (Sandbox Code Playgroud)

更新了Rails 4的语法:

Mail.where(validated: true)
    .group(:country)
    .count
Run Code Online (Sandbox Code Playgroud)


air*_*tyh 19

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

这应该为您提供具有country属性和count属性的记录.