问题描述
枚举属性很棒,我想使用它们。但是将枚举值映射为整数将使维护代码和数据库变得困难。同样,我的数据库将与我的代码高度耦合,我认为我应该认为这是一件坏事。
Enum attributes are great and I want to use them. But mapping enum values to integer would make it hard to maintain both code and database. Also my database would be highly coupled with my code which I think I should consider that a bad thing.
我知道我可以使用哈希来组织带有键的枚举属性/值对,但仍然能够使用数组并映射到数据库中的字符串值会好很多。
I know I can use a hash to organize an enum attribute with key/value pairs, but still it would be a lot better to be able to use an array and map to string values in database.
有什么方法可以将枚举映射到默认为字符串?
Is there any way to map enum to strings by default?
推荐答案
据我所知,Active Record的内置枚举功能是不可能的。但是,有一些流行的第三方宝石可以做到这一点。与Active Record最为接近的匹配可能是和。
As far as I know it's not possible with Active Record's built-in enum functionality. However, there are a few popular 3rd party gems that do this. The closest match to what comes with Active Record are probably enumerize and SimpleEnum.
但是,如果您正在寻找一些不同的东西,我会推荐(完整披露:我写了)。这是关于枚举和SimpleEnum之间的区别vs ClassyEnum:
However, if you're looking for something a little different, I'd recommend ClassyEnum (full disclosure: I wrote it). Here are some of my notes on the difference between enumerize and SimpleEnum vs ClassyEnum:
ClassyEnum旨在解决分散
与不同枚举有关的条件逻辑的问题。您仍然可以将其
用于没有逻辑的简单集合,但是当您确实需要
添加逻辑(并且几乎可以肯定)时,可以将其推入
个人枚举类并利用多态性。
ClassyEnum was designed to solve the problem of having scattered conditional logic related to the different enums. You can still use it for simple collections that don't have logic, but when you do need to add logic (and you almost certainly will), you can push that into the individual enum classes and take advantage of polymorphism.
这篇关于将枚举值映射到字符串类型而不是整数的可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!