PostgreSQL, Rails and :order => problem
Asked Answered
E

3

7

I have the following line in my ActiveRecord model:

class Record < ActiveRecord::Base
    has_many :users, :through => :record_users, :uniq => true, :order => "record_users.index ASC"

This is intended to enable me to read out record.users in a way that I order using an index field in the record_users model.

The problem is that this fails on PostgreSQL with the following error:

ActionView::TemplateError (PGError: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list

Is there a way to fix the statement to make it work?

Eijkman answered 11/11, 2009 at 11:56 Comment(1)
Can you post the generated SQL?Blinking
S
10

I suppose you could call it a bug in ActiveRecord. PosgreSQL is a bit more restrictive than MySQL. You can help out ActiveRecord by setting up the association like this instead:

class Record < ActiveRecord::Base
  has_many :users,
   :through => :record_users,
   :select => 'DISTINCT users.*, record_users.index',
   :order => "record_users.index ASC"
Sketchy answered 11/11, 2009 at 18:21 Comment(6)
You can, since it is. MySQL is a bit more permissive and non-standard in what it accepts.Outcome
I don't get it - what's wrong with my solution above? I'd like to know, because I'm using it in my own project running on Postgres ;)Sketchy
Casper, I don't think james was saying it was a bad solution ;-) Also, is that a typo - DISTINCT?Eijkman
Also, my question was - is there a way to fix the statement to make it work?. Your answer worked perfectly!Eijkman
Cool. I guess I assumed that James had voted my answer down and that his comment was the explanation for it - guess not ;)Sketchy
I mean i have duplicate records!Trichloroethylene
J
2

Just posted this issue on rails's issue tracker on github (copied from lighthouse ticket so we could bring it back.. it was marked invalid):

https://github.com/rails/rails/issues/520

Promote it if you want this fixed nicely! :)

Jeffery answered 11/5, 2011 at 16:19 Comment(0)
C
1

I ran into something similar before and I believe it's an AR bug related to PGSQL (https://rails.lighthouseapp.com/projects/8994/tickets/1711-has-many-through-association-with-order-causes-a-sql-error-with-postgresql).

I got around it by dropping the DISTINCT (:uniq) directive and resolved the uniq records another way. Kind of a bummer though.

Classmate answered 11/11, 2009 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.