Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 has many through and order scope

I have this model:

class User < ActiveRecord::Base
  has_many :customers, -> { order('customers.name ASC') }
  has_many :stores, -> { order('company_stores.id ASC').uniq }, through: :customers
end

When I attempt to

user.stores

I have this error:

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

because Rails performs a SELECT DISTINCT of company_stores.*, but in the ORDER BY also appears customers.name

Should I give up order in associations?

like image 951
John Smith Avatar asked Nov 05 '13 17:11

John Smith


1 Answers

As the error message suggests, PG requires that the order expression is included in the select, so select('stores.*, company_stores.id').order('company_stores.id ASC').uniq or similar should do the trick.

like image 154
Mike Campbell Avatar answered Oct 19 '22 12:10

Mike Campbell