I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?
相关问题
- Question marks after images and js/css files in ra
- Why does const allow implicit conversion of refere
- Using :remote => true with hover event
- Eager-loading association count with Arel (Rails 3
- How to specify memcache server to Rack::Session::M
相关文章
- Ruby using wrong version of openssl
- Right way to deploy Rails + Puma + Postgres app to
- AWS S3 in rails - how to set the s3_signature_vers
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- How to add a JSON column in MySQL with Rails 5 Mig
- “No explicit conversion of Symbol into String” for
- form_for wrong number of arguments in rails 4
You can use an array or hash for this purpose (in your environment.rb):
or alternatively an enumeration class, which allows you to enumerate over your constants as well as the keys used to associate them:
which you can then derive from:
and use like this:
I put them directly in the model class, like so:
Then, when using the model from another class, I reference the constants
If it is driving model behavior, then the constants should be part of the model:
This will allow you to use the built-in Rails functionality:
Alternatively, if your database supports enumerations, then you can use something like the Enum Column plugin.
Rails 4.1 added support for ActiveRecord enums.
Declare an enum attribute where the values map to integers in the database, but can be queried by name.
See its documentation for a detailed write up.
You can also use it within your model inside a hash like this:
And use it like this:
You can also group constants into subjects, using a module --
And then have,