ruby-on-rails - 在 Rails 中将模型常量实现为列表或枚举
问题描述
我有一个模型常数,它基本上是environments
如下值:
class Account
has_many :account_configs
accepts_nested_attributes_for :account_configs
ACCOUNT_ENVS = %w[development staging production].freeze
end
class AccountConfig
validates :account, presence: true
validates :environment, inclusion: {in: Account::ACCOUNT_ENVS}
end
该常数ACCOUNT_ENVS
也用于view
. 现在这对我的情况很有效,但我应该在这里使用enum
吗?如果是,我该如何使用它?
解决方案
您可以进行以下迁移,
class ChangeEnvironmentOfAccountConfig < ActiveRecord::Migration
def up
change_column :account_configs, :environment, :integer, default: 0
end
end
默认值始终设置为development
。
在模型中,
class AccountConfig
enum environment: %w(:development, :staging, :production)
end
config = AccountConfig.create
config.environment
# => "development"
config.production?
# => false
config.production! #updates the object
AccountConfig.development # acts as scope to filter with environment
推荐阅读
- javascript - 在 TypeScript 中包装 Firebase 承诺
- laravel - Laravel 6.6,DO 上的负载均衡器和 redis 托管集群...登录时 CSRF 令牌出现问题
- javascript - ES6 - 获取同一天的所有活动对象[差异小于或等于1天]
- sql - 使用原始查询时,Doctrine 语句未正确返回数据
- android - 带有保存按钮的 SharedPreferences
- javascript - 如何在对象对象 JavaScript 中查找特定值
- javascript - 将 excel 二维数组转换为包含列名的嵌套属性对象
- python - 如何从 mxnet nd 数组中访问类标签的索引?输出必须是使用函数输入的标签名称的索引
- python - 如何比较烧瓶中的两个密码
- tensorflow - Google Colab:TPU 不支持的数据类型:double,由输出 cond_8/Merge:0 引起