将枚举值映射到字符串类型而不是整数的可能性

编程入门 行业动态 更新时间:2024-10-28 06:25:27
本文介绍了将枚举值映射到字符串类型而不是整数的可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

枚举属性很棒,我想使用它们。但是将枚举值映射为整数将使维护代码和数据库变得困难。同样,我的数据库将与我的代码高度耦合,我认为我应该认为这是一件坏事。

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.

更多推荐

将枚举值映射到字符串类型而不是整数的可能性

本文发布于:2023-10-23 03:31:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   而不是   可能性   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!