如何为 rails 中的列设置一些默认值?

How can I set some default values to a column in rails?

所以我的 rails 网络应用程序中有一个 table,在 "db/schema.rb" 文件中看起来像这样:

create_table "checks", force: cascade do |t|
  t.text "name"
  t.datetime "created_at", precision: 6, null: false
  t.datetime "updated_at", precision: 6, null: false
  t.string "status", default: "pending", null: false
end

我的问题是,如何将三个 "default" 值设置为状态。我只希望值 "pending"、"scheduled" 和 "runnin" 能够设置为 "status".

的值

不知何故,我没有找到相关信息。只设置一个默认值,但这不是我想要的。

非常希望能快速回答。谢谢!

你必须使用模型来做,下面是做的例子。在您的迁移中添加以下内容

t.integer "status", default: 1, null: false

现在在你的模型中 app/models/checks.rb 输入以下代码

  STATUS = {
    pending: 0,
    scheduled: 1,
    runnin: 2
  }.freeze

  enum status: STATUS

现在您还可以像下面这样访问

check = Check.first
puts check.status

所以你实际上是以整数形式保存枚举,它的值是你在模块中定义的。这是一种方法。

要扩展 Kamal 的答案,您不必定义散列然后设置枚举。您可以在那里传递使用符号数组。

enum status: %i[pending scheduled runnin]

当您可以 access/view 具有 Check.statuses 的枚举散列时,这将 return {pending: 0, scheduled: 1, runnin: 2} 就像他说的:

check = Check.first
puts check.status

Rails' 枚举还允许您访问范围和实例方法。

Check.pending # returns ALL pending checks

# if check belongs to any other model....
other = Other.first
other.checks.pending # returning all pending checks that belong to the instance of other model

#boolean checks
check = Check.first
check.pending? # returns true or false if the check has the enum 0

# setting the enum
check = Check.first
check.pending! # sets and saves the check's status as pending

然后设置默认值,就像 Kamal 所说的那样

t.integer, :status, default: 1, null: false, index: true

至于设置 3 个不同的默认值,你不能。您需要选择一个枚举值并将其设置为默认值,如上所述。

创建 Check 时,您可以使用上面显示的 ! 或在创建参数中设置值,如果您想将其设置为默认值以外的值:

pending_status = Check.statuses[:pending]
Check.create(status: pending_status)

这种方法很有用,因此您不必担心枚举的位置,如果它们在以后的开发中发生变化的话。

Rails' enum docs