简体   繁体   中英

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:

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:

pupils.sort_by(&:level_asc)

with a method level_asc that just returns their level. 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..

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:

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

You can do this in the order clause, by using something like:

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"]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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