class User
has_many :calendars
has_many :cars, through: :calendars
end
class Calendar
has_many :cars
end
class Car
# attribute `issued_at`
end
我需要按issued_at
的汽车订购用户。因此,根据大孩子的属性issued_at
对父母进行排序。
到此为止:
@q = User.active.joins(:cars).order('cars.issued_at').group('users.id')
但是我得到了
column "cars.issued_at" must appear in the GROUP BY clause or be used in an aggregate function
答案 0 :(得分:1)
使用distinct
而不是group
来消除重复项:
@q = User.active.joins(:cars).order('cars.issued_at').distinct
答案 1 :(得分:1)
这是复制品仓库:https://github.com/localhostdotdev/bug/tree/ordering-parents-by-grand-children
进行相同的查询时,我没有看到任何错误,则问题必须在您的active
范围内。
这是带有scope :active, -> { where(active: true) }
的完整查询:
SELECT "users".*
FROM "users"
INNER JOIN "calendars" ON "calendars"."user_id" = "users"."id"
INNER JOIN "cars" ON "cars"."calendar_id" = "calendars"."id"
WHERE "users"."active" = ?
GROUP BY users.id
ORDER BY cars.issued_at
LIMIT ?
我无法重现您的问题。