Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL, Rails and :order => problem

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?

like image 573
cmaughan Avatar asked Nov 11 '09 11:11

cmaughan


2 Answers

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"
like image 64
Casper Fabricius Avatar answered Oct 14 '22 05:10

Casper Fabricius


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! :)

like image 2
Lance Carlson Avatar answered Oct 14 '22 06:10

Lance Carlson