尝试通过关系显示所有项目时发生Postgres错误

时间:2013-11-19 00:33:16

标签: ruby-on-rails ruby rails-postgresql pg

这适用于SQLite3,但不适用于PostgreSQL。

我得到的错误是PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

我正在尝试使用代码显示exercises中的所有groupcurrent_user.group.exercises

这是关系

一个小组有很多锻炼,锻炼有很多练习

在我的群组模型中,我有has_many :exercises, through: :workouts

有什么想法吗?

编辑1:

这是SQL rails正在生成:

SELECT DISTINCT "exercises".* 
FROM "exercises" 
  INNER JOIN "workout_exercises" ON "exercises"."id" = "workout_exercises"."exercise_id" 
  INNER JOIN "workouts" ON "workout_exercises"."workout_id" = "workouts"."id" 
  INNER JOIN "groups_workouts" ON "workouts"."id" = "groups_workouts"."workout_id" 
WHERE "groups_workouts"."group_id" = 2 
ORDER BY exercise_order, workout_order

这是错误:

PG::InvalidColumnReference: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ..." WHERE "groups_workouts"."group_id" = 2 ORDER BY exercise_o...
                                                             ^
: SELECT DISTINCT "exercises".* FROM "exercises" INNER JOIN "workout_exercises" ON "exercises"."id" = "workout_exercises"."exercise_id" INNER JOIN "workouts" ON "workout_exercises"."workout_id" = "workouts"."id" INNER JOIN "groups_workouts" ON "workouts"."id" = "groups_workouts"."workout_id" WHERE "groups_workouts"."group_id" = 2 ORDER BY exercise_order, workout_order

2 个答案:

答案 0 :(得分:3)

所以这是一个uniq约束异常。在模型上,我有has_many :exercises, through: :workouts, uniq: true,Postgres不喜欢。

要修复错误,我将uniq约束从模型移动到实际查询。所以在这种情况下,我刚做current_user.group.exercises.uniq

这只能解决我的问题。在某些情况下,我希望在模型级别有​​一个uniq约束,但我还没有找到一种方法来做到这一点。

答案 1 :(得分:1)

每个SQL变体的规则与它接受的表达式略有不同。例如,有关此问题的信息,请参阅Simulating MySQL's ORDER BY FIELD() in Postgresql和相关链接。如果你给出了你正在生成的SQL的细节,你可能会得到更具体的建议。