0

I have MyModel with two attributes, a :label string and an :group integer which groups these strings. The labels for these groups come from an array of strings GROUP_LABELS. For my html view, I wanted to create a select control with grouped options.

The resulting hash of nested arrays needs to be:

{ 'Group Label 1': [[ 'Label 1.1', 1 ],[ 'Label 1.2', 2 ]],
  'Group Label 2': [[ 'Label 2.1', 3 ],[ 'Label 2.2', 3 ] ... ]}
wribln
  • 355
  • 2
  • 13

1 Answers1

0

My solution was:

{}.tap{ |h| [
  MyModel.all.order( :group ).chunk{ |r| r.group }.each{ |g,i| 
    h[ GROUP_LABELS[ g ]] = i.map{ |i| [ i.label, i.id }}]}

MyModel.all.order( :group )gives me the ARel, sorted by the grouping attribute. .chunkcreates an iterator over the ARel considering the :group value, within that loop I create the hash entries per :group.

I would like to share this with you as I could not find a suitable solution elsewhere.

wribln
  • 355
  • 2
  • 13