在使用 PostgreSQL 的 RoR 7.1.3 应用程序中,我有一个枚举定义为:
create_enum :foo_states, %i[active inactive]
create_table :foo do |t|
t.enum :state, enum_type: :foo_states, default: :active, null: false
end
class Foo < ApplicationRecord
enum :state, %i[active inactive], default: :active, validate: true
end
当我实例化一个新对象时,它工作正常:
Foo.new
=> #<Foo state: "active">
Foo.create(state: :bar).errors
=> #<ActiveModel::Errors [#<ActiveModel::Error attribute=state, type=inclusion, ...
但是保存记录时它不会保留其
state
:
foo = Foo.new
=> #<Foo state: "active">
foo.save
=> #<Foo state: nil>
# same on .create
Foo.create
=> #<Foo state: nil>
这是预期的行为吗?如果是这样,我如何错误地使用此功能?
您在数据库层中创建枚举,并使用
active
和 inactive
字符串作为可能的值
但是当你在模型中写入时
enum :state, %i[active inactive], default: :active, validate: true
这意味着您将尝试将
0
保存为 active
,并将 1
保存为 inactive
(索引为整数)
而不是在模型中将枚举定义为哈希这样的方式
enum :state, { active: 'active', inactive: 'inactive' }, default: :active, validate: true