Ruby on rails 使用枚举进行Rails验证
我的盒子模型中有一个枚举Ruby on rails 使用枚举进行Rails验证,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,我的盒子模型中有一个枚举 enum box_type: [:wooden, :plastic, :metal, :paper] 我希望我的长方体模型的长方体类型属性仅为其中之一,因此: validates :box_type, inclusion: {in: box_types.keys } 看起来它应该可以完美地工作,但我在创建我的长方体模型时还有一个默认值,设置如下: class CreateBoxes < ActiveRecord::Migration[5.0] def ch
enum box_type: [:wooden, :plastic, :metal, :paper]
我希望我的长方体模型的长方体类型属性仅为其中之一,因此:
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
问题:
我做错了什么?
有没有更好的方法只允许数据库列中的特定值?
枚举在数据库中存储整数,而不是字符串。尝试将列类型更改为整数,并将默认值更改为0
声明一个枚举属性,其中值映射到
数据库,但可以按名称查询
@messages={:box_type=>["is not included in the list"]}, @details={:box_type=>[{:error=>:inclusion, :value=>nil}]}