我有这个模型:
class User < ActiveRecord::Base
has_many :customers, -> { order('customers.name ASC') }
has_many :stores, -> { order('company_stores.id ASC').uniq }, through: :customers
end
当我尝试
user.stores
我有这个错误:
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
因为Rails执行了SELECT DISTINCT of company_stores.*
,但在ORDER BY
中也出现了customers.name
我应该放弃协会的秩序吗?
正如错误消息所暗示的那样,PG 要求在选择中包含顺序表达式,因此select('stores.*, company_stores.id').order('company_stores.id ASC').uniq
或类似方法应该可以解决问题。