rails-为枚举字段应用默认值 [英] rails - apply default value for enum field

查看:48
本文介绍了rails-为枚举字段应用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的enum字段设置一个默认值,以防止它为nil.我做了以下事情:

I want to have a default value for my enum field to prevent it from being nil. I did the following:

# db/schema.rb
create_table "templates", force: :cascade do |t|
  t.integer  "status"
end

# app/models/template.rb
class Template < ActiveRecord::Base
  STATUSES = [:draft, :published]
  enum status: STATUSES
  after_initialize :init

  def init
    self.status ||= STATUSES.index(:draft)
  end
end

我在本地环境中获得了预期的结果.但在heroku中并不完全.在将状态更新为 nil 后,我需要将其作为默认值 draft ,但是在这种情况下,它变为 nil ,而已发布范围仍包含更新的行.

I get the expected results in my local environment. But not quite in heroku. I need it to be the default value draft after updating status to nil, but in this context it becomes nil and yet the published scope still includes the updated row.

$ heroku run rails console

> Template.published.pluck :id
=> [1, 2]

> Template.find(1).update(status:nil)
Template Load (4.4ms)  SELECT  "templates".* FROM "templates" WHERE "templates"."id" = $1 LIMIT 1  [["id", 1]]
Template Load (4.4ms)  SELECT  "templates".* FROM "templates" WHERE "templates"."id" = $1 LIMIT 1  [["id", 1]]
(1.7ms)  BEGIN
(1.7ms)  BEGIN
(1.1ms)  COMMIT
(1.1ms)  COMMIT
=> true

> Template.find(1).status
=> nil

> Template.published.pluck :id
=> [1, 2]

这是使用枚举的正确用例吗?我错过了我的heroku环境吗?

Is this the correct use case to use an enum? Is there a peculiarity with my heroku environment that I'm missing out?

推荐答案

您可以从数据库声明中设置默认值.

You can set the default value from the database declaration.

create_table :templates do |t|
  t.column :status, :integer, default: 0
end

然后,按如下所示映射关系

And then, map the relationship as following

class Template < ActiveRecord::Base
  enum status: { draft: 0, published: 1 }
end

这篇关于rails-为枚举字段应用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆