首页 > 解决方案 > 将枚举值添加到 ruby​​ on rails 模型,并将其设为所有新模型实例的默认值

问题描述

我在模型中定义了一个这样的枚举

enum status: { started: "started", passed: "passed", failed: "failed" }

我想为draft: "draft"它增加价值

但据我了解,我必须以某种方式运行迁移才能将其添加到数据库中。我该怎么做?可能是个愚蠢的问题,请多多包涵,谢谢。

:edit 感谢您的反馈

我还需要将新添加的枚举值设为所有新模型的默认值。这可能需要迁移,但我将如何生成它?

标签: ruby-on-railsrubyenumsmodel

解决方案


您可以将枚举值添加到列表中。

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

推荐阅读