Rails Rails enum 怎样保存 nil 值

armstrong · 2016年10月12日 · 最后由 armstrong 回复于 2016年10月14日 · 1890 次阅读

我只是想在 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 弄成这样:

Solution

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

Rails 4.2 直接model.industry = nil没问题,你 rails 什么版本?

rails version=4.0.13

需要 登录 后方可回复, 如果你还没有账号请 注册新账号