0

As the title states, I would like to do a sort_by such that my Course model can be sorted by its "year" column, but in such an order that I can specify.

Possible years are:

Freshman
Sophomore
Junior
Senior

So I'd like to make those into an array:

array_of_years = ["Freshman", "Sophomore", "Junior", "Senior"]

And sort my Courses by their year, in the order of that array.

For instance (pseudocode follows, I just made up the syntax to explain what I'm asking for):

Course.all.sort_by{ |course| course.year, array_of_years }

This would sort them in order of the array_of_years array, by ordering all Courses with a "year" column of "Freshman" first, and "Senior" last.

And if I wanted them sorted from Senior to Freshman, then I'd do:

Course.all.sort_by{ |course| course.year, array_of_years.reverse }

Or I could simply rearrange the array_of_years array to my liking and use the first block of code.

Is there a way to sort like this in Ruby/Rails?

4

1 回答 1

3
Course.all.sort_by { |course| array_of_years.index(course.year) }

撤销:

Course.all.sort_by { |course| -array_of_years.index(course.year) }
于 2013-10-03T20:24:06.997 回答