0

Good day, I was wondering, is it possible if i make a selection with group_by like so

  @p = Performance.includes(place: [:category]).
  order("places.title ASC").
  group_by{|p| p.place.category}

so if i want a specific category to be the first, what do i do?

EDIT 1

in view a parse through the results by @p.each do |p|

Elmor
  • 4,775
  • 6
  • 38
  • 70

2 Answers2

2

The return value of group_by is just a normal hash, so you can apply sort_by on it to place your desired category first:

group_by { |p| p.place.category }.sort_by { |k,v| (k=="category name") ? "" : k }

where category name is the name of the category you want to prioritize (the empty string make it come first in the sort results, everything else will just be sorted alphabetically).

This will transform the hash into an array. If you want to keep the data in hash form, wrap the result in Hash[...]:

Hash[group_by { |p| p.place.category }.sort_by { |k,v| (k=="category name") ? "" : k }]

See also this article on sorting hashes: http://www.rubyinside.com/how-to/ruby-sort-hash

UPDATE:

A slightly less processor-intensive alternative to sorting:

grouped = group_by { |p| p.place.category }
Hash[*grouped.assoc("category name")].merge(grouped.except("category name"))

There might be a simpler way to do this, but basically this prepends the key and value for "category name" to the head of the hash.

Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
0

Although I think shioyama's answer might help you, I doubt you really need the sort process. As shio correctly states, the return value of your sort_by is a hash. So why dont you just access the value, which you want as the first value, simply by using it as hash-key?

Atastor
  • 741
  • 3
  • 11
  • in view a parse through the results by @p.each do |p| – Elmor Sep 04 '12 at 11:05
  • I agree that there should be a better way to do this. I've posted an alternative which just prepends the desired category group to the front of the hash as one alternative. – Chris Salzberg Sep 04 '12 at 12:38