2017-01-17 115 views
0

我有一个枚举在我的盒子模型导轨和枚举验证

enum box_type: [:wooden, :plastic, :metal, :paper] 

,我想我的盒子模型的box_type属性只是其中的一个,所以:

validates :box_type, inclusion: {in: box_types.keys } 

似乎它应该工作完美无瑕,但我也有一个默认值,当创建我的箱子模型,像这样设置:

class CreateBoxes < ActiveRecord::Migration[5.0] 
    def change 
    create_table :boxes do |t| 
     ... 
     t.string :box_type,  null: false, default: "paper" 
     ... 
     t.timestamps 
    end 
    end 
end 

当我尝试在控制台中创建一条记录时,我得到一个回滚。 错误:

@messages={:box_type=>["is not included in the list"]}, @details={:box_type=>[{:error=>:inclusion, :value=>nil}]} 

问题:

  1. 我在做什么错?
  2. 有没有更好的方法只允许我的数据库列中的特定值?

回答

1

enum在数据库中存储整数,而不是字符串。试着改变列的类型为整数,并默认为0

Declare an enum attribute where the values map to integers in the database, but can be queried by name.