枚举属性很棒,我想使用它们。但是将枚举值映射为整数将使维护代码和数据库变得困难。同样,我的数据库将与我的代码高度耦合,我认为我应该认为这是一件坏事。
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最为接近的匹配可能是枚举和 SimpleEnum 。
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.
但是,如果您正在寻找一些不同的东西,我会推荐 ClassyEnum (完整披露:我写了)。这是我的一些笔记关于枚举和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:
无类枚举(枚举,SimpleEnum)非常适合简单使用情况下,您只需要一个字段表示一组固定的值之一。这个解决方案的主要问题是,它鼓励在模型,控制器和视图中分散个条件。 使用这些宝石是很诱人的,因为它们是工具最简单的工具,但是IMO并没有为提供长期收益,而是最简单的情况。
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旨在解决分散与不同枚举有关的条件逻辑的问题。您仍然可以将其用于没有逻辑的简单集合,但是当您确实需要添加逻辑(并且几乎可以肯定)时,可以将其推入个人枚举类并利用多态性。
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.
更多推荐
将枚举值映射到字符串类型而不是整数的可能性
发布评论