枚举属性很棒,我想使用它们。但是将枚举值映射为整数将使维护代码和数据库变得困难。而且我的数据库将与我的代码高度耦合,我认为我应该认为这是一件坏事。
我知道我可以使用散列来组织带有键/值对的枚举属性,但是仍然能够使用数组并将其映射到数据库中的字符串值会更好。
默认情况下,有什么方法可以将枚举映射到字符串吗?
最佳答案
据我所知,Active Record的内置枚举功能是不可能的。但是,有一些流行的第三方 gem 可以做到这一点。最接近Active Record的匹配项可能是enumerize和SimpleEnum。
但是,如果您正在寻找一些不同的东西,我建议您使用ClassyEnum(完整披露:我已经写过)。以下是some of my notes关于枚举和SimpleEnum与ClassyEnum之间的区别:
Class-less enums (enumerize, SimpleEnum) are great for simple use cases where you just need a field to represent one of a fixed set of values. The main issue I have with this solution is that it encourages conditionals scattered throughout your models, controllers and views. It's tempting to use these gems because they are the simplest to implement, but the long term payoff just isn't there IMO for anything but the simplest cases.
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.
关于ruby-on-rails - 将枚举值映射到字符串类型而不是整数的可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105813/