Question

I've got a simple class like:

class Foo
    include DataMapper::Resource
    property :id, Serial
    property :bar, Text, lazy: false
    property :created_on, DateTime, default: lambda { |r,p| DateTime.now }
end

I want to select them, grouped by bar and ordered by max(created_on). The SQL I need is:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY MAX("created_on") DESC

but I don't know how to get this with DataMapper.

I've tried something like:

Foo.all(fields: [:bar], unique: true, order: [:created_on.desc.max])

but you can't use max like that. I can't find out how to do it.

Can you help?

Was it helpful?

Solution

It seems as if using the max aggregate is not necessary. By ordering in descending order of the created_on column its going to find the MAX and go from there.

You could probably get away with:

Foo.all(fields: [:bar], unique: true, order: [created_on.desc])

without using .max in the order.

This would be same as:

SELECT "bar" FROM "foo" GROUP BY "bar" ORDER BY "created_on" DESC

Hope this works.

Also take a look at http://datamapper.org/docs/find.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top