没有相应存储/列的Rails枚举



我有以下模型:

class Operation < ApplicationRecord
enum state: [:started, :restarted, :reloaded, :stopped]
end

但是,Postgres数据库中的基础表没有state列。尽管我可以为state属性赋值并保存模型实例,但state只是没有保存:

op = Operation.new state: :started
op.save!
=> true

这是我想要的行为,我只想以与使用attr_accessor属性相同的方式使用它,但有一些额外的约束。

问题是,以这种方式使用enum可以吗?还是这是一种未定义的行为,将来可能会改变/修复?

官方文件没有回答这个问题https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Enum.html

UPD:是的,正如@ricks所说,我可以通过实现同样的目标

attr_accessor :state
validates :state, inclusion: { in: %i[started reloaded restarted stopped] }, allow_nil: true

但CCD_ 6的使用对我来说更方便,因为如果值不在允许的列表中,它会在分配时抛出异常。

您也可以使用属性api来实现这一点。

class Operation < ApplicationRecord
attribute :state
enum state: [:started, :restarted, :reloaded, :stopped]
end

这将为您提供您正在查找的所有枚举异常(以及其他枚举方法(。

虽然文档中没有,但建议将其作为rails问题的解决方案。

您不需要Enum,只需要做

class Operation < ApplicationRecord
attr_accessor :state
STATE_KEYS = [:started, :restarted, :reloaded, :stopped].freeze
validates :state, inclusion: { in: STATE_KEYS }
end

最新更新