1

I'm using gem enumerize in my project. For now I have this:

class MyAddress < ActiveRecord::Base

  enumerize :country, in: [:country1, :country2, :country3], default: :country2

end

Now I want to convert state to be enumerize. Obviously, each country has its own states. How can I do something like this:

class MyAddress < ActiveRecord::Base

  enumerize :country, in: [:country1, :country2, :country3], default: :country2
  enumerize :state, in: [{ country1: [:state11, :state12, :state13], country2: [:state21, :state22, :state23], country3: [:state31, :state32, :state33]} ]

end

Is it possible?

bjhaid
  • 9,592
  • 2
  • 37
  • 47
Incerteza
  • 32,326
  • 47
  • 154
  • 261

1 Answers1

2

The gem documentation doesn't indicate this sort of thing is possible. And it makes sense that it wouldn't. An enumeration is simply a mapping between a key (or name) and a value (an integer). In your example you're essentially looking to map the country (key) to an array of non-numeric values. So that doesn't make sense.

I would suggest you organize your states by country with code comments and just let the enumeration be simple.

enumerize :state,
          in: [
            # Country 1
            :state11, :state12, :state13,
            # Country 2
            :state21, :state22, :state23
          ]

Enumerations aren't ever really "easy" to remember what the key is for a given value stored. So you'll just have to come up with a way to make it a bit simpler to look up (as I've attempted to do above).

pdobb
  • 17,688
  • 5
  • 59
  • 74
  • and how would dynamically determine which country does a state belong to? – Incerteza May 20 '14 at 13:32
  • You could probably use ranges like `if (state11..state13).cover?(state) then country1`. This could be in a method like `get_country_from(state)` or whatever. – pdobb May 20 '14 at 13:35