build_histories(name,status,updated_at)
foo1, Queued, 2017-01-08 13:46:59
foo2, Failed, 2017-01-02 13:46:59
foo3, Success,2017-01-03 13:46:59
foo4, Queued, 2017-01-04 13:46:59
foo5, Failed, 2017-01-05 13:46:59
foo6, Success,2017-01-09 13:46:59
我尝试了这个并返回
BuildHistory.joins(app_build: :app).where("build_histories.bundle like ?","%#{params}%").order("CASE WHEN status = 'Queued' THEN 1 ELSE 2 END, status", "updated_at DESC")
foo1, Queued, 2017-01-08 13:46:59
foo4, Queued, 2017-01-04 13:46:59
foo2, Failed, 2017-01-02 13:46:59
foo5, Failed, 2017-01-05 13:46:59
foo3, Success,2017-01-03 13:46:59
foo6, Success,2017-01-09 13:46:59
但是我想把它排序为“排队”总是在顶部,之后“失败/成功”应该在updated_at desc
订单
实施例
foo1, Queued, 2017-01-08 13:46:59
foo4, Queued, 2017-01-04 13:46:59
foo6, Success,2017-01-09 13:46:59
foo5, Failed, 2017-01-05 13:46:59
foo3, Success,2017-01-03 13:46:59
foo2, Failed, 2017-01-02 13:46:59
供参考:我试过基于this
尝试以下
BuildHistory.joins(app_build: :app).where("build_histories.bundle like ?","%#{params}%").select("*, CASE WHEN build_histories.status = 'Queued' THEN 1 ELSE 2 END as tmp_order").order("tmp_order, build_histories.updated_at desc")
我能够得到结果但是在状态栏中我得到状态= 1或2而不是“排队/成功/失败”
请帮助
答案 0 :(得分:3)
如果您使用MySql
,可以按field
.order("FIELD(status, 'Queued'), updated_at DESC")
对于postgres
.order("status = 'Queued' DESC, updated_at DESC")
答案 1 :(得分:1)
尝试
BuildHistory.order("CASE WHEN status = 'Queued' THEN 1 ELSE 2 END", "updated_at DESC")
注意:我自己没有检查过代码,但我认为它应该有用。