We’re all used to writing enums in Rails as
class Comment
enum visibility: [:private, :public]
end
This is often improved by adding a hash to explicitly map the symbols to their integers like
class Comment
enum visibility: {
private: 0,
public: 1
}
end
Have you ever looked at the database for this model and asked “what does visibility 1
mean”?
id | visibility | content |
---|---|---|
1 | 0 | Comments are awesome |
2 | 1 | Comments rule! |
We go back to the class and we decide to add strings. Now we have the enum reading like.
class Comment
enum visibility: {
private: "private",
public: "public"
}
end
I find this unnecessarily verbose. Surely we could go back to the original implementation and pass a type
argument.
class Comment
enum visibility: [:private, :public], type: :string
end
This will give us the best of both worlds. A clear syntax and clear database values.
Next steps
- How could this be implemented in Rails?
- Should this be implemented in Rails?
- Would this be better as a separate gem?
- OMG why would you want to use strings as enums?
- OMGG string enums don’t work in Rails?