I really like Rails 4 new Enum feature, but I want to use my enum
enum status: [:active, :inactive, :deleted]
in every model. I cannot find any way how to declare for example in config/initializes/enums.rb
and include every model
I'm very new in Ruby on Rails
and need your help to find solution
In Ruby on Rails, an enum is an attribute where the values map to integers in the database and can be queried by name. For example, we could define an enum for the status attribute, where the possible values are pending , active , or archived . Ruby on Rails added support for enums in Rails 4.1.
UPDATE 2019: Enums are fine to use in Android since ART replaced DALVIK as runtime environment stackoverflow.com/a/56296746/4213436.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Use ActiveSupport::Concern
this feature created for dry
ing up model codes:
#app/models/concerns/my_enums.rb
module MyEnums
extend ActiveSupport::Concern
included do
enum status: [:active, :inactive, :deleted]
end
end
# app/models/my_model.rb
class MyModel < ActiveRecord::Base
include MyEnums
end
# app/models/other_model.rb
class OtherModel
include MyEnums
end
Read more
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With