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 如何检索group_中每个组的第一个值?_Ruby On Rails_Ruby_Postgresql - Fatal编程技术网

Ruby on rails 如何检索group_中每个组的第一个值?

Ruby on rails 如何检索group_中每个组的第一个值?,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,如何在使用group by的查询中找到所有第一个/顶部值?因此,我希望找到每个分组月份的第一条记录: class Log < ActiveRecord::Base belongs to :foo attr_accessible :month, :votes, :foo_id # ... end 类日志

如何在使用group by的查询中找到所有第一个/顶部值?因此,我希望找到每个分组月份的第一条记录:

class Log < ActiveRecord::Base
  belongs to :foo
  attr_accessible :month, :votes, :foo_id
  # ...
end
类日志

因此,在上面的模型中,我想检索每个月投票最多的记录。这些记录已经按票数降序排列。

这将根据月份过滤所有数据,您可以在每个循环中进入其中并从中获取第一条记录

month_wise = Log.all.group_by { |t| t.created_at.beginning_of_month }

month_wise.each do |month|
puts month.first.inspect
end
您可以使用和:


tops=Log.all.group_by{l|l.created_at.month}.map(&:first)

如果使用Rails,可以使用

Log.all.group_by{ |l| l.created_at.month }.transform_values(&:first)