是否可以删除枚举的默认值?我有以下内容:
class Post < ApplicationRecord
enum status: {
auto_draft: 'auto_draft',
draft: 'draft',
future: 'future',
pending: 'pending',
private: 'private',
publish: 'publish',
trash: 'trash'
}, _suffix: true
end
以及后续迁移中的以下内容:
execute <<-SQL
ALTER TABLE posts
ADD status enum(
'auto_draft',
'draft',
'future',
'pending',
'private',
'publish',
'trash'
) NOT NULL AFTER id;
SQL
现在,如果我在不传递状态的情况下创建帖子,它将使用auto_draft
,这是不正确的行为:我希望没有默认值。这是可能的,如果答案是肯定的,该怎么办。
答案 0 :(得分:1)
您可以使用Rails迁移将列更改为空
change_column_null :posts, :status, true
这将采用表名,列名,并将其设置为null true
https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column_null
我不熟悉设置枚举的方式。我通常会
#not null column with default
add_column :posts, :status, :integer, default: 0, null: false
# for a nullable column...
add_column :posts, :status, :integer
然后在模型中
class Post < ApplicationRecord
...
enum status: %i[...]
end