[英]Pull most recent records for distinct users in ruby on rails
The database is something like this: 该数据库是这样的:
id testID date
1 100 10/12/2012
2 100 10/13/2012
3 102 10/14/2012
Let's call this database "Test" 我们将此数据库称为“测试”
I want the output to be an ActiveRecord:Relation that contains 我希望输出为包含以下内容的ActiveRecord:Relation
id testID date
2 100 10-13-2012
3 102 10-14-2012
I know how to get the results as an array, as following: 我知道如何以数组形式获取结果,如下所示:
result = []
testIDList = Test.uniq.pluck(:testID)
testIDList.each do |tID|
result = result + Test.where(:testID => tID).order('date DESC').limit(1)
end
In this case, result is an array of ActiveRecord:Relation But I want result to be an ActiveRecord:Relation, I tried to use merge no success. 在这种情况下,结果是ActiveRecord:Relation的数组,但是我希望结果是ActiveRecord:Relation,因此我尝试使用merge没有成功。
尝试
result = Test.order(:date).group(:testID)
Try this: 尝试这个:
result = Test.where(:testID => testIDList)
.select("max(`date`) as recent_date").group(:testID)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.