I am trying to create an enum on my model and I would like one of the states to be "new"
e.g.
enum status: { stale: 0, new: 1, converted: 2 }
It seems rails rejects this with the following error.
You tried to define an enum named "status" on the model "Lead", but this will generate a class method "new", which is already defined by Active Record.
I understand why this is happening, but I was wondering if there is no way to get around this?
Enums or Enumerated types are special data types that set variables as a set of predefined constants. In other languages enumerated data types are provided to use in this application. Javascript does not have enum types directly in it, but we can implement similar types like enums through javascript.
An enum is a special "class" that represents a group of constants (unchangeable variables). Enums come in two flavors string and numeric .
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.
The error clearly states that you cannot have an enum with new
key as it will conflict with an existing ActiveRecord
method. There is no way out of this.
This issue is not new and it has been discussed before.
I would recommend you to read
enum: Option not to generate "dangerous" class methods
As per Godfrey Chan
, Collaborator of Rails:
In this case, if you want to use enum, you are probably better off renaming your label to something else. This is not unique to enums – a lot of Active Record features generates methods for you and usually there aren't ways to opt-out of those generated methods.
Gonna give this one a close for now....
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