rails枚举,没有相应的存储/列

toiithl6  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(187)

我有以下型号:

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

但是使用 enum 对我来说更方便,因为如果值不在允许列表中,它会在赋值时抛出异常。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题