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

标签 ruby-on-rails ruby-on-rails-4 enumeration

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

我知道我可以使用散列来组织带有键/值对的枚举属性,但是仍然能够使用数组并将其映射到数据库中的字符串值会更好。

默认情况下,有什么方法可以将枚举映射到字符串吗?

最佳答案

据我所知,Active Record的内置枚举功能是不可能的。但是,有一些流行的第三方 gem 可以做到这一点。最接近Active Record的匹配项可能是enumerizeSimpleEnum

但是,如果您正在寻找一些不同的东西,我建议您使用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/

相关文章:

ruby-on-rails - 我可以以只读模式打开 rails 控制台吗?

ruby-on-rails - rspec 和第一次测试试验

html - 如何创建 Rails 4 离线 Web 应用程序?

java - 遍历 hastable 键的枚举会引发 NoSuchElementException 错误

ruby-on-rails - 像 Rails 控制台一样使用 Sequelize

ruby-on-rails - 如何将 ActiveSupport::TimeWithZone 实例格式化为指定格式

ruby - 如何在 Rails 4.1 中只在路由上写入一次 path_names 并使其可用于所有路由?

c# - 如何将两个枚举与自定义函数结合起来?

c++ - C++ 中的 IEnumerable?

ruby-on-rails - 是否有插件或 gem 可以帮助我在 rails 中执行 "invite a friend"功能?