Ruby Hash is including extra values for a single key

Viewed 160

I've tried to build a hash multiple ways, but when I use it in a grouped_options_for_select tag, there are extra values that aren't in my original hash. Here are two ways I've tried to build my hash:

UNITS_OF_MEASURE_GROUPED = {
  "Dry" =>     ["oz", "lb", "g", "kg"],
  "Liquid" =>  ["floz", "gal", "ml", "L"],
  "Other" =>   ["each"]
}.freeze

and a bit more explicit and very wordy:

UNITS_OF_MEASURE_GROUPED = {}
UNITS_OF_MEASURE_GROUPED[:dry] = ["oz", "lb", "g", "kg"]
UNITS_OF_MEASURE_GROUPED[:liquid] = ["floz", "gal", "ml", "L"]
UNITS_OF_MEASURE_GROUPED[:other] = ["each"]
UNITS_OF_MEASURE_GROUPED.freeze

But the grouped_options_for_select always includes "floz" and "each" in the first section ("dry"). Please see attached image.

I forgot to add my form element code:

<%= form.select :unit_of_measure, grouped_options_for_select(UNITS_OF_MEASURE_GROUPED) %>

As per Guiseppe in another comment, I tried <%= form.select :unit_of_measure, UNITS_OF_MEASURE_GROUPED %> with the same result.

Something that does seem really weird is when I go into the console after triggering an error, my UNITS_OF_MEASURE_GROUPED hash shows this:

{:dry=>["oz", "lb", "g", "kg", ["floz", "gal", "ml", "L"], ["each"]], :liquid=>["floz", "gal", "ml", "L"], :other=>["each"]}

My guess is that's screwing up the HTML and getting confused. Does that help?

What am I missing? Thank you SO much in advance.

enter image description here

2 Answers

I'd be inclined to concur with the suspicion that something mangling your hash is to blame. To find out what, try a deeper freeze:

UNITS_OF_MEASURE_GROUPED = {
  dry: %w(oz lb g kg),
  liquid: %w(floz gal ml L),
  other: %w(each)
}.transform_values(&:freeze).freeze

This'll (hopefully) throw a FrozenError, and accompanying illuminating stack trace, from wherever deep in the app/framework is screwing with it.

The problem is the way you are calling form.select inside the erb tag. You are supposed to pass a collection but instead, you are passing a string as the second argument. You should pass UNITS_OF_MEASURE_GROUPED instead of grouped_options_for_select(UNITS_OF_MEASURE_GROUPED) as in the following example:

<%= form.select :unit_of_measure, UNITS_OF_MEASURE_GROUPED %>.

If you look at rails guides you can find an example.

The select helper

Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:

ActionView::Helpers::FormOptionsHelper#select requires a collection as parameter.

Edited.

It could be the generetion of hidden fileds that you get by default Try the following

<%= form.select :unit_of_measure, UNITS_OF_MEASURE_GROUPED, {include_hidden: false} %>

See Documentation for details.

Related