Rails:按大孩子的属性订购父母

时间:2019-05-07 17:52:50

标签: ruby-on-rails ruby postgresql activerecord

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

2 个答案:

答案 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 ?

我无法重现您的问题。