Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "DISTINCT ON" in conjunction with Arel / ActiveRecord?

I have a Message ActiveRecord Model and I want to select all messages that have a distinct conversation_partner_id. I'm currently specifying the DISTINCT ON clause as a string but I was wondering if it could be provided as an Arel expression instead and whether there would be a benefit. My statement looks as follows:

Message.select('DISTINCT ON ("messages"."conversation_partner_id") messages.*').from(t)

where t is a union of the messages table and specified as a somewhat complex Arel expression. I leave it out as it is independent of the SELECT issue and works just fine.

The following code does not work:

Message.select([
  Arel::Nodes::DistinctOn.new(Message.arel_table[:conversation_partner_id]),
  Message.arel_table[Arel.star]
]).from(t)

It results in malformed SQL as it places a comma after the DISTINCT ON () clause:

SELECT DISTINCT ON ("messages"."conversation_partner_id"), "messages".* ...
                                                         ^
like image 326
t6d Avatar asked May 11 '15 11:05

t6d


1 Answers

If you try this:

Message.arel_table
       .project(Arel.star)
       .distinct_on(Message.arel_table[:conversation_partner_id])
       .to_sql

You get this:

SELECT DISTINCT ON ( \"messages\".\"conversation_partner_id\" ) * FROM ...
like image 117
Elena Unanyan Avatar answered Oct 23 '22 17:10

Elena Unanyan