문제

Relationship User has_many :kits

User model and named scope:

  scope :top5_users,
    joins(:kits).
    select("users.*, count(kits.id) AS kits_count").
    group("users.id, kits.id").
    order("kits_count DESC").
    limit(5)

Getting PG::Error: ERROR: ORDER BY "kits_count" is ambiguous

도움이 되었습니까?

해결책

That error message implies you have a column in users called kits_count, possibly maintained by a callback. If so you could more easily just:

scope :top5_users,
    order("kits_count DESC").
    limit(5)

If not ...

Support for column aliases is mixed among RDBMS vendors, and you could probably use:

order("count(kits.id) desc")

If you knew the column number you could:

scope :top5_users,
    joins(:kits).
    select("count(kits.id) AS kits_count, users.*").
    group("users.id").
    order("1 DESC").
    limit(5)

Take the kits.id out of the group by or you'll get 1 for every count.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top