Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 同时计数和分组_Ruby On Rails - Fatal编程技术网

Ruby on rails 同时计数和分组

Ruby on rails 同时计数和分组,ruby-on-rails,Ruby On Rails,我有一个邮件模型,模式如下: 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 =&

我有一个
邮件
模型,模式如下:

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 )
这将告诉我组(我需要一个命令,我不知道如何写)

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

我想知道我是否可以一次分组数数

Mail.find( :all, :select => 'count(*) count, country', :group => 'country', :conditions => ['validated = ?', 't' ], :order => 'count DESC', :limit => 5) 邮件查找( :全部, :select=>“计数(*)计数,国家”, :group=>country, :条件=>['validated=?','t'], :order=>count DESC', :限制=>5) 这将为您提供具有国家属性和计数属性的记录。

请尝试:

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

我不确定count是否接受
: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之前调用limit(因为
#count
返回
ActiveSupport::OrderedHash
):

Rails 4的更新语法:


我也必须将数据与城市名称进行分组,并显示计数每个城市在特定条件下有多少行。我就是这样做的:

CityData.where(:status => 1).group(:city_name).count
这项研究的成果是:

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

应该使用true而不是't'@airportyh Rails API说ActiveRecord.find已弃用()。你知道在Rails 3上实现这一点的最佳方法吗?@Daniel:我以前也这么想过,但仔细看看:上面写着“移动或弃用”,实际上它已经移动到ActiveRecord::FindMethods#find。(我相信您仍然应该调用Mail.find在其新位置访问此方法。)要使用限制选项,您必须执行以下操作:Mail.limit(10).order(“count_all desc”).count(group::country)。与tee的建议类似。对于指定条件,我建议在模型上使用作用域,或者使用where选项。
Mail.where(validated: true)
    .order("count_all desc")
    .limit(5)
    .count(group: :country)
Mail.where(validated: true)
    .group(:country)
    .count
CityData.where(:status => 1).group(:city_name).count
{:Mumbai => 10, :Dublin => 7, :SF => 9}