Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.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 如何在DataMapper中使用order by中的聚合?_Ruby_Datamapper_Ruby Datamapper - Fatal编程技术网

Ruby 如何在DataMapper中使用order by中的聚合?

Ruby 如何在DataMapper中使用order by中的聚合?,ruby,datamapper,ruby-datamapper,Ruby,Datamapper,Ruby Datamapper,我有一个简单的类,如: class Foo include DataMapper::Resource property :id, Serial property :bar, Text, lazy: false property :created_on, DateTime, default: lambda { |r,p| DateTime.now } end 我想选择它们,按条分组,按最大值排序(已创建)。我需要的SQL是: SELECT "bar" FROM "

我有一个简单的类,如:

class Foo
    include DataMapper::Resource
    property :id, Serial
    property :bar, Text, lazy: false
    property :created_on, DateTime, default: lambda { |r,p| DateTime.now }
end
我想选择它们,按条分组,按最大值排序(已创建)。我需要的SQL是:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY MAX("created_on") DESC
但我不知道如何用DataMapper获得这个

我试过这样的方法:

Foo.all(fields: [:bar], unique: true, order: [:created_on.desc.max])
但你不能那样使用max。我不知道怎么做


您能帮忙吗?

似乎没有必要使用最大聚合。通过对列上创建的_按降序排序,它将找到最大值并从那里开始

你可能会侥幸逃脱:

Foo.all(fields: [:bar], unique: true, order: [created_on.desc])
没有在订单中使用.max

这与:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY "created_on" DESC
希望这能奏效

也来看看

我也遇到了同样的问题,无法找到“好”的解决方案。我所做的事情是直接调用SQL或添加一个聚合字段(我认为这在您的情况下不起作用)。