简体   繁体   中英

How do I sort a collection / enum by a custom method in ruby/rails?

In Rails, let's I have a collection of Categories:

@categories = Category.order('name asc')

One of these categories has the name "New". I'd like to have the "New" category first in the collection, and the rest alphabetical.

I'd like to only do one database query. I'd like this to be as concise as possible.

If the one query limit was not in place, I know I could fetch the "New" category, and then fetch the rest of the categories in order by name, and then "unshift" the new category to the @categories collection, but there must be a better way!

@new = Category.where(name: 'name').first
@categories = Category.where("name != ?", 'Name').order('name asc')
@categories.unshift(@new)

Any ideas?

I think I've come up with something pretty good:

@categories = Category.order('name asc').partition { |cat| cat.name == 'New' }

Or, even better:

@categories = Category.order('name asc').partition { |cat| cat.name == 'New' }.flatten

This gives me one query and the "New" category first in the collection.

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