Ask A Question

Notifications

You’re not receiving notifications from this thread.

Storing Constant Date in Rails

Michael Victor asked in Rails

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?

Reply

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.

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.