我有一个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 )
这将告诉我团体(我需要一个订单,我不知道怎么写)
@top5 = Mail.count(:all,:group => 'country',:conditions => [ "validated = ?" , "t" ], :limit => 5 )
这将告诉我每组中有多少邮件
我想知道我是否可以一次性分组和计算
尝试:
Mail.count(:group => 'country', :conditions => ['validated = ?', 't'])
我不确定算是否接受:limit
了.
编辑:
我认为这更具可读性:
Mail.count(:group => :country, :conditions => {:validated => true})
使用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之前调用limit(因为#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
Mail.find( :all, :select => 'count(*) count, country', :group => 'country', :conditions => ['validated = ?', 't' ], :order => 'count DESC', :limit => 5)
这应该为您提供具有country属性和count属性的记录.