我想为我的续集模型使用 auto_validations。文档说:
The auto_validations plugin automatically sets up the following types of validations for your model columns:
type validations for all columns
not_null validations on NOT NULL columns (optionally, presence validations)
unique validations on columns or sets of columns with unique indexes
max length validations on string columns
使用此代码(mysql2 适配器):
class Sequel::Model
plugin :schema
plugin :validation_helpers
plugin :auto_validations, :not_null=>:presence
end
unless DB.table_exists? (:unit_types)
DB.create_table :unit_types do
primary_key :id
String :name, :null => false
end
end
class UnitType < Sequel::Model(:unit_types)
end
创建的表架构是:
CREATE TABLE `unit_types` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
在 irb 中测试它:
irb(main):009:0> UnitType.create()
Sequel::ValidationFailed: name is not present
irb(main):010:0> UnitType.create(name: '')
Sequel::ValidationFailed: name is not present
很好,但是最大长度验证不起作用:
irb(main):016:0* UnitType.create(name: "abc"*1000)
Sequel::DatabaseError: Mysql2::Error: Data too long for column 'name' at row 1
怎么办?
@ymonad 完全正确:问题是由稍微过时的 Sequel 版本引起的!
我是一名优秀的程序员,十分优秀!