Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the array for an Enum model attribute?

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
like image 978
Bmxer Avatar asked Aug 11 '16 18:08

Bmxer


People also ask

Can an enum have an array?

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.

How do I get all the values in an enum list?

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.

Can enum have attributes?

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).


1 Answers

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.

like image 170
Simone Carletti Avatar answered Sep 22 '22 06:09

Simone Carletti