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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With