DISTINCT ON with Ruby on Rails and Arel

456 views Asked by At

I have the following table structure (simplified)

id | version | slug |     state
-------------------------------
 1 |       1 |    A | published
 2 |       2 |    A |     draft
 3 |       1 |    B | published
 4 |       1 |    C | published
 4 |       2 |    C | published
 4 |       3 |    C |     draft

I want to get all records with the highest version number, grouped by slug and where the state is published. The SQL for this looks like this:

SELECT DISTINCT ON(slug) *
FROM guides
WHERE state = 'published'
ORDER BY slug ASC, version DESC;

And packed into Rails:

Klass.select('DISTINCT ON(slug) *').where(state: :published).order(slug: :asc, version: :desc)

Is there any nicer syntax available? In the past I used a bit of Arel, but I don't seem to get the distinct part correct.

1

There are 1 answers

1
Simone Carletti On

The AR query is already quite nice and simple. I don't think you can get anything different and I don't see anything wrong with it.

The only thing you can change is to use DISTINCT(slug) rather than DISTINCT ON(slug) *.