I am trying to use distinct on in rails with a scope, I've created a method in my model like this:
def self.fetch_most_recent_by_user(scope)
scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end
When I execute this I get and error like:
TestModel.fetch_most_recent_by_user(TestModel.includes(:user))
ERROR: syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...
On searching on DISTINCT ON
I found out that it should be the first element in a select statement for postgres to make it work.
I want to prepend the DISTINCT ON
in the select statement. I have tried clearing the old select statements using except(:select)
which I got from here, but it doesn't work because the includes(:user)
prepends users attributes first while doing a left join.
I am using Rails 4.0.13
and Postgres 9.4.12
. Any help is appreciated.