简体   繁体   English

Rails-sort_by,但保持活动记录关系

[英]Rails - sort_by but keep active record relation

I'm working on a project where I have a pupil model, which has an attribute called level, an integer between 1 and 3. At the moment the default sorting by level has been over ridden: 我正在一个项目中,我有一个瞳孔模型,该模型具有一个称为level的属性,该属性在1到3之间。目前,按级别进行的默认排序已被覆盖:

enum level: { "level_1" => 2, "level_2" => 0, "level_3" => 1 }

And I've been asked not to change this. 而且有人要求我不要更改此设置。 I now need to sort by level ascending, and have been using sort_by: 我现在需要按级别升序进行排序,并且一直在使用sort_by:

pupils.sort_by(&:level_asc)

with a method level_asc that just returns their level. 使用一个只返回其级别的方法level_asc。 The problem with this is it is returning an array which is screwing up my pagination. 问题是它正在返回一个数组,这使我的分页搞砸了。

Is there any way I can sort by level ascending, ignoring the previously stated rule, and return an active record relation? 我有什么方法可以按级别升序排序,而忽略前面提到的规则,并返回活动记录关系? I've tried attr_accessors with no joy.. 我尝试过attr_accessors并没有任何乐趣。

Thanks in advance 提前致谢

EDIT: 编辑:

I've tried simply merging 3 where queries, however I'm using rails 4.~ and I don't have access to the 'OR' method which would work perfectly: 我已经尝试过简单地合并3的查询,但是我使用的是rails 4.〜,但是我无法访问完美运行的'OR'方法:

Pupil.where(level: 1).or(where(level: 2)).or(where(level: 3))

If there is any way for me to do the above line in rails 4 then I'll be sorted 如果有任何方法可以在滑轨4中执行上述操作,则将对我进行排序

You can do this in the order clause, by using something like: 您可以在order子句中执行以下操作:

Pupil.order('level = 2 DESC, level = 0 DESC, level = 1 DESC, id ASC').collect { |pupil| [pupil.id, pupil.level] }
# Pupil Load (0.9ms)  SELECT "pupils".* FROM "pupils" ORDER BY level = 2 DESC, level = 0 DESC, level = 1 DESC, id ASC
# => [[4, "level_1"], [5, "level_1"], [6, "level_1"], [8, "level_1"], [2, "level_2"], [7, "level_2"], [1, "level_3"], [3, "level_3"], [9, "level_3"], [10, "level_3"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM