ruby-on-rails - 将枚举值添加到 ruby on rails 模型,并将其设为所有新模型实例的默认值
问题描述
我在模型中定义了一个这样的枚举
enum status: { started: "started", passed: "passed", failed: "failed" }
我想为draft: "draft"
它增加价值
但据我了解,我必须以某种方式运行迁移才能将其添加到数据库中。我该怎么做?可能是个愚蠢的问题,请多多包涵,谢谢。
:edit 感谢您的反馈
我还需要将新添加的枚举值设为所有新模型的默认值。这可能需要迁移,但我将如何生成它?
解决方案
您可以将枚举值添加到列表中。
enum status: { started: "started", passed: "passed", failed: "failed", draft: "draft" }
如果枚举是一个数组,您必须确保仅将新值添加到数组的末尾,否则记录将具有错误的状态。
至于将其设为新记录的默认值,我会在模型中执行此操作,而不是在数据库中...
class MyModel < ApplicationRecord
before_save :initialize_status
private
def initialize_status
self.status ||= 'draft' if new_record?
end
end
推荐阅读
- flutter - 卡在肘上,将状态更改为 2 个小部件
- r - 如何更改条形图中单个条形的位置?
- python - Python; 使用初始字符列表从其他列表中检索完整单词?
- rust - 将特征的边界引用作为 IntoIterator 时的生命周期冲突
- javascript - 如何管理同一页面中多次包含的相同代码的 CSS 选择器?
- javascript - 如何通过参数访问子对象
- jags - 在 Fedora 33 上安装 rjags
- mysql - MySQL 合并来自多个 JSON 行的数组
- reactjs - React Select 在选择第二个选项之前不会更新
- java - 使用Java的数字总和