All threads / Storing Constant Date in Rails

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?

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.