Skip to main content

Storing Constant Date in Rails

Rails • Asked by Michael Victor

What is the best way to store a set of constants like country names, currencies, city lists in a rails app?

I was thinking of having a model named Constants that stores all this data and another model ConstantMaps that is polymorphic that maps the constants to the various other models

Is this a right approach?


If you want them to be editable, then storing them in a model makes sense. You can easily add and update them.

Otherwise if you really want them to be true constants, you could set a constant in Ruby in a Rails initializer file like so:

# config/initializers/countries.rb
COUNTRIES = [
  "United States",
  "Canada",
  #... etc
]

And then you could reference the COUNTRIES variables in your code in other places.


Also, if you don't need this as a global constant you can also do something similar in a helper. But from the sound of it, you'd want a global constant for this use case.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.