how to use DISTINCT ON with mysql using ActiveRecord

So you want all user visits with last visited time.

Instead of use DISTINCT function, you can use GROUP with MAX function.

Query looks like

Events.group(:user_id).maximum(:time)

This Outputs your desired results

{21=>Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23=>Thu, 20 Dec 2018 06:42:10 UTC +00:00}

Hope this works for you.

FYI
DISTINCT ON(columns). is PostgreSQL Syntax.

Leave a Comment