I wanted to get the array of symbols(:foo,:bar) available in an Enum field(:status).
class MyModel < ActiveRecord::Base
enum status: [:foor, :bar]
end
Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).
As explained in the Enum guide, if you have an enum field called status
you access the mapping using the plural form:
MyModel.statuses
=> {"foor"=>0, "bar"=>1}
The keys are the enum values, the values are an incremental integer assigned based on the order of the enum definition.
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