如何在Rails3中的Active Record中按天和年分组

con*_*t01 5 mysql activerecord group-by ruby-on-rails ruby-on-rails-3

我正在尝试在rails 3中重新创建以下mysql查询

 select count(id), year(created_at), month(created_at) from table where published_state = 'published' group by year(created_at), month(created_at);
Run Code Online (Sandbox Code Playgroud)

我尝试过类似的东西:

results = Table.select('count(id), year(created_at), month(created_at)').where('published_state LIKE ?', 'published').group('year(created_at), month(created_at)')
Run Code Online (Sandbox Code Playgroud)

但它不会返回我想要的东西.

我只是得到了回报

[#<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >,
 #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >]
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

谢谢!

gre*_*tes 16

试试这个:

Table.where(:published_state => 'published').
  group('year(created_at)').group('month(created_at)').count(:id)
Run Code Online (Sandbox Code Playgroud)

结果的格式不是我所期望的(它是一个数组键[year, month]和计数值的哈希)但是它可能会满足你的目的吗?