我有帶有列的 Job 表job_type,job_type可以是top,hot或normal。現在,當我列出所有作業時,我希望top首先顯示作業,然后是hot作業,最后是normal作業。我還想按降序對作業進行排序(created_at: :desc)。我有以下范圍
class Job < ApplicationRecord
scope :hot_jobs, -> { where(job_type: 'hot') }
scope :top_jobs, -> { where(job_type: 'top') }
scope :normal_jobs, -> { where(job_type: 'normal') }
end
我試過了。
在控制器中我嘗試了這樣的事情
@jobs = Job.hot_jobs.order(created_at: :desc).or(Job.top_jobs.order(created_at: :desc)).or(Job.normal_jobs.order(created_at: :desc))
但上面的代碼不起作用。上面的代碼結果與Job.all.order(created_at: :desc)
那么如何按以下順序列出作業,Top Jobs然后Hot Jobs是Normal Jobs. 如果我使用陣列,我可以做一些黑客攻擊,但我不想轉換ActiveRecord#Relations為陣列,因為這會產生問題will_paginate并且我不能includes用來阻止N 1查詢
我正在使用 Rails 6.0.4.1
更新
我將job_type列更改為integer但我無法做到
@jobs = Job.active.order(job_type: :asc, created_at: :desc).limit(48)
這被問題解決了。
uj5u.com熱心網友回復:
只需在您的訂單中使用 case 陳述句。
Rails 6 中的技巧是將其包裝在 Arel.sql 中,否則會出現“非屬性引數”錯誤
@jobs = Job.all.order(
Arel.sql(
"case when job_type = 'top' then 1
when job_type = 'hot' then 2
else 3 end asc"), created_at: :desc)
如果您在作業中有默認訂單范圍,只需更改order為reorder
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446685.html
