Rails ActiveRecord Model.uniq.pluck: id does not work with postgres

I have an application for demo rails 4 trying to do the following: Collection.order('created_at ASC').uniq.pluck :name It works under sqlite but explodes in postgres with the following error:

 (0.9ms) SELECT DISTINCT "collections"."name" FROM "collections" ORDER BY created_at ASC PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list LINE 1: ...collections"."name" FROM "collections" ORDER BY created_at... 

Is this a mistake or how to fix it?

+4
source share
3 answers

I really tried to solve this problem on active_admin. https://github.com/gregbell/active_admin/issues/2324

Now the solution seems to be Collection.reorder('name asc').uniq.pluck :name , this will overwrite default_scope or previous order and order the collections with name . What is strange here reorder works, but how order causes a problem ...

+2
source

This seems like a problem with PostgreSQL. ( Rails 3 DISTINCT QUERY )

To solve this problem, you can use select instead:

Collection.select([:name, :created_at]).order('created_at ASC').uniq.select(:name)

Or you could have Ruby get the names uniquely, not SQL:

Collection.order('created_at ASC').pluck(:name).uniq

+2
source
 Collection.select([:id, :created_at]).order('created_at ASC').uniq.pluck(:id) 
+1
source

Source: https://habr.com/ru/post/1489941/


All Articles