'ActiveRecord Get Max Value Without Loading

I need to get the last record with a certain value, but without loading it.

I have to do something like:

Thing.where(cool: true).where(created_at: Thing.where(cool: true).maximum(:created_at))

The above is a way to do it, but it does a 2nd query to get the maximum value first. I want to do it all in one query and get the SQL equivalent of something = max(etc).

Just before someone mentions it: .last doesn't work because it returns an object not a relation.

In order words, I need to do .last but returning a relation instead of objects.



Solution 1:[1]

Try this way:

Thing.where("cool=1 AND created_at=(SELECT MAX(created_at) FROM things WHERE cool=1)")

On Rails 7, when I tested your query, the database is queried only once.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin M?sior