Enum in Rails

Tram Ho

When web programming, you will probably use a ‘status’ field. But with a status field, how can you save many different states, maybe you will think of the case using a boolean data type, but with a boolean data type we can only save. storing two types of state that is true or false , and feeling it is not very clear huh. For example, you want more than 2 states such as [:pending, :accept, :reject] example. So in this article I would like to introduce to you a technique in rails that can handle this situation is Enum .
To use Enum , you need to declare the data type as integer instead of boolean or string . Enum allows you to map strings values ​​with integer values. To declare using Enum very simple, you just need to write the following code in the model.

Looking at the example above, we can summarize the definition of Enum as Enum is a set of possible values ​​of an attribute. To use Enum , simply call the values ​​you declare for the property you declare as Enum . You can access Enum by an object, open the console and test.

For example :

Or do you want to retrieve all records whose status is pending :

You can get all values ​​of status by

By default, Rails will store enum values ​​from 0 and above. You can reset those values ​​by declaring

Use prefix and suffix in enum

If you do not want to call Enum values ​​by default, but instead want to add other suffix prefixes before that value for clarity, in Rails we can easily declare the following. Example with suffix :

Normally, to retrieve records whose status is pending we only need RegisterCourse.pending . But if you declare like that and intentionally access will lead to an error message:

Because there is a declaration of _suffix: true , to call it we have to call the following

By default, rails will take the suffix as the field name, in this case it is status . If you do not want to use by default, you can declare and name another as follows:

Similarly we use it with prefix

or put a different prefix name

So that’s what I want to introduce to you in this article.

Reference https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html

Share the news now

Source : Viblo