1

I’ve started migrating a Rails 4 application from SQLite to PG (PostgreSQL). I have a lot of scopes that I use for ordering (eg: scope :default_order, ->{order(:name)} ) that I merge to order my records in controllers.

With PG, when I do this:

User.joins(:shipments, :person).merge(Person.default_order).distinct

It complains that:

 ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list

All my scopes are well encapsulated but now, it seems I need to manually write the select clause (with DISTINCT and dig into the model to pick the proper ordering column... like this answer: https://stackoverflow.com/a/1717152/178266). That doesn't sound right to me.

I've tried to 'add' to the select in the ordering scope (to keep it encapsulated, something like: .select(arel_table[:weight])) but it doesn't work.

The irony is that I've migrated all the manual selects ("DISTINCT ...") statements to ActiveRecord.uniq with Rails 3.2, but it looks like I need to do it all over again in the other direction!

Unless somebody has a good suggestion...

PS: The only workaround I see right now is the ugly:

User.joins(:shipments, :person).merge(Person.default_order).select('DISTINCT(users.*), people.name')
2
  • I don't think you can escape that PG restriction (here's a similar question). This is still ugly but provides a way to keep things encapsulated: User.select("users.*").joins(:shipments, :person).merge(Person.select("people.name").default_order).distinct. Commented Mar 19, 2016 at 4:37
  • cschroed, that doesn't help: because often enough, the order clause contains columns from another table. Commented Mar 28, 2016 at 9:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.