Enum method in Ruby on Rails

<h1>A little history.</h1>

Enumerize gem was written by Sergey Nartimov as a new way to handle specific attributes in a database column. Thus, developers could manage attributes that could only take predefined values. For example, if you could only have 3 types of enterprises, you could use something like this:

enumerize enterprise_type, in: ['large', medium', 'small']

This also creates new methods like @enterprise.enterprise_type_large? for handle the value in the column. This is good!
You could to use them as select input in the view:

# Enumerize
# Enum

The idea of this was to handle those attributes on the model. The Rails core team saw that many developers were using it in this way on their projects

From Rails 4 was included as module to ActiveRecord::Enum. But it was not until Rails 5 that enum support was completed.

In Rails 4 does not exists supports for somethings as _preffix or _suffix.
If you’d 2 enum methods with the same values for example:

enum gift_status: [:open, :closed]
enum door_status: [:open, :closed]

This brings errors because creates 2 same method for “open? or closed?”.

In Rails 5.x was added this new support for those methods so you could to do:

enum gift_status: [:open, :closed], _prefix:true
enum door_status: [:open, :closed], _suffix::my_door

This fixed these errors.

# With _prefix
# With _suffix

Enum offers methods to set values, for example:

@door.my_door_open? => false
@door.my_door_open? => true

1- When should I use enum or enumerize?
R: Whenever there’s only a few values your attributes can take.
2- What’s better between enum and enumerize?
R: Both are good, they work similarly. Rails core is always updating the enum module and adding new features, and so is enumerize.
3- What’s difference between enum and enumerize?
R: The major difference between them it is that enum works with integer datatype and enumerize with strings as the underlying native type.
4- Could I create default values with both?
R: Yes, with enum you must to do with migration file adding default argument. With enumerize you can do it in the model using the default parameter.

ActiveRecord::EnumSource code

Escribe tu comentario
+ 2