Sql 在RubyonRails中为不同的用户提取最新记录
数据库如下所示:Sql 在RubyonRails中为不同的用户提取最新记录,sql,ruby-on-rails,Sql,Ruby On Rails,数据库如下所示: id testID date 1 100 10/12/2012 2 100 10/13/2012 3 102 10/14/2012 让我们将此数据库称为“测试” 我希望输出是一个ActiveRecord:Relation,其中包含 id testID date 2 100 10-13-2012 3 102 10-14-2012 我知道如何以数组的形式获取结果,如下所示: result = [] testIDList = Test.un
id testID date
1 100 10/12/2012
2 100 10/13/2012
3 102 10/14/2012
让我们将此数据库称为“测试”
我希望输出是一个ActiveRecord:Relation,其中包含
id testID date
2 100 10-13-2012
3 102 10-14-2012
我知道如何以数组的形式获取结果,如下所示:
result = []
testIDList = Test.uniq.pluck(:testID)
testIDList.each do |tID|
result = result + Test.where(:testID => tID).order('date DESC').limit(1)
end
在本例中,结果是ActiveRecord:Relation的数组
但我希望结果是一个ActiveRecord:Relation,我尝试使用合并,但没有成功 试试这个:
result = Test.where(:testID => testIDList)
.select("max(`date`) as recent_date").group(:testID)
试一试
Test.order(:date)起作用,但与.group(:testID)一起失败。我想它不知道如何将它们组合在一起。你确定这个字段的名称是testID only吗。Test.where(:testID=>testIDList)与Test。选择(“最大(
date
)作为最近的_日期”)也失败:(
result = Test.order(:date).group(:testID)