gpt4 book ai didi

ruby-on-rails - 基于枚举值的自定义顺序

转载 作者:行者123 更新时间:2023-12-04 01:56:01 25 4
gpt4 key购买 nike

我为角色定义了这个枚举:

enum role: {ordinary: 0, manager: 1, admin: 2}

我想按以下顺序订购一组对象:
admin (first all admins)
ordinary (then all ordinaries)
manager (and lastly all managers)

这可能吗?

最佳答案

对此的解决方案:

class YourModel < ActiveRecord::Base
ROLE_ORDERS = [2, 0, 1]

scope :order_by_role, -> {
order_by = ['CASE']
ROLE_ORDERS.each_with_index do |role, index|
order_by << "WHEN role=#{role} THEN #{index}"
end
order_by << 'END'
order(order_by.join(' '))
}
end

那么您的查询将像这样简单:
YourModel.order_by_role

生成的查询是:
SELECT * from your_models
ORDER BY ( CASE
WHEN role=2 THEN 0
WHEN role=0 THEN 1
WHEN role=1 then 2
END
)

来自 this 的良好引用

关于ruby-on-rails - 基于枚举值的自定义顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37599510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com