我只是想在 enum
字段保存一个 nil
值,居然报错 enum is not valid industry
migration
create_table :xx_ops do |t|
t.industry :integer
end
model
class ModelName < ActiveRecord::Base
INDUSTRY = {"online_travel" => 100 ,"entertainment" => 110 ,"other" => 120}
enum industry: INDUSTRY
end
执行的 action
def create
model = ModelName.new
model.industry = nil
end
居然报错 enum is not valid industry
查了文档 enum
方法,居然没有 allow_blank: true 之类的设置。
官方给的 best practice 是加一个 default: 0, here. 可是之前同事发布时,mysql 执行 default 时间太长的引发了故障,不敢用这个。
意淫了一把,把 model 弄成这样:
model
class ModelName < ActiveRecord::Base
INDUSTRY = {"online_travel" => 100 ,"entertainment" => 110 ,"other" => 120, '' => nil}
enum industry: INDUSTRY
end
设置 model.industry = nil
,竟然可以
action
model = ModelName.new
model.industry = '' # good
model.industry = nil # good
original from here