I am pulling a flat hash of parameters from an external API into my Rails app. I need to present these parameters to the user in a select field.
The hash is formatted as follows:
[["Name", "ID", "Category"]]
I’d like to present this as a grouped select. But I believe the grouped_select tag takes a hierarchical hash, not a flat hash?
Is there an easy way to restructure this hash into a structured hash? i.e.,
['CategoryA', [['Name-A1','ID-A1'],['Name-A2', 'ID-A2']]
For reference, I’m currently handling the hash in my controller like this
@hash = session["hash"].map { |h| [ h["name"], h["id"], h["category"] ] }
and in the view
<%= f.select :hash_id, @hash %>
This gives me an unordered list of options. How can I group on h["category"]?
Thanks for any pointers.
EDIT
By the way, I;ve already tried group_by as it seemed the obvious way to go. But I’m getting can't convert String into Integer. Perhaps I’m not using it correctly?
hash.group_by {|h| h["category"] }.map { |h| [ h["name"], h["id"], h["category"] ] }
1 Answer