I was trying to answer this question where I got this issue.
I have a user model having id
, email
and first_name
columns. So in single query I want to select users with distinct first_name
, sort them by email
and pluck their ID
.
How can I do this?
what won't work:
User.select(:first_name).uniq.pluck(:id)
because it fires this SQL
SELECT DISTINCT "users"."id" FROM "users"
. This is selecting distinct id from user. But we want to select distinct first_nameUser.order("email DESC").pluck(:id).uniq
SQL generated:
SELECT "users"."id" FROM "users" ORDER BY email DESC
. This will not work because the sql generated is not checking for uniqueness of first_name.