如何在使用 Model.uniq.pluck(:field) 获取的 Rails 集合上设置顺序



我正在收集一组问题的sale_stage,以便在我的rails应用程序视图中显示 - 只要我希望它们按字母顺序排列(我没有):

@stages = Question.uniq.pluck(:sale_stage)

我想要的是选择相同的唯一sale_stage名称,但按question_id排序 - 因为这将在我的页面上以正确的顺序显示阶段。我试过使用:

@stages = Question.order(:id).uniq.pluck(:sale_stage)

但这会引发以下错误:

SELECT DISTINCT "questions"."sale_stage" FROM "questions"   ORDER BY "questions"."id" ASC
PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...estions"."sale_stage" FROM "questions"   ORDER BY "questions...
                                                         ^
: SELECT DISTINCT "questions"."sale_stage" FROM "questions"   ORDER BY "questions"."id" ASC
Completed 500 Internal Server Error in 251ms
ActiveRecord::StatementInvalid (PG::Error: ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...estions"."sale_stage" FROM "questions"   ORDER BY "questions...
                                                         ^
: SELECT DISTINCT "questions"."sale_stage" FROM "questions"   ORDER BY "questions"."id" ASC):

我不完全确定这意味着什么 - 这个语句无效错误的答案对我没有多大帮助。任何人都可以建议如何按question_id排序此查询吗?

@stages = Question.order(:id).pluck(:sale_stage).uniq

最新更新