在 Rails 模型/表中验证存在与 null false [英] Validates presense vs null false in Rails models/tables
问题描述
我在玩 Rails 管理员,我注意到了一些事情.
I was playing around with Rails admin and I noticed something.
在模型中定义如下的属性,在Rails admin中算作必需"
Attributes which are defined as below in model, counted as "Required" in Rails admin
validates :user, presence: true
但是,下表中定义的属性(架构/迁移)仍被视为可选"
However, attributes which are defined as below in table (schema/migration) still counted as "Optional"
t.datetime "created_at",:null => false
我会假设这两个是相同的,除了验证错误弹出的级别.我错了还是这是 Rails 管理员错误?这两者是否都确保成功保存该字段是必需的,还是有区别?
I would have assumed that both of these are identical except perhaps the level from which the validation error pops up. Am I wrong or is this a Rails admin error? Are both of these ensuring that this field will be required for a successful field save or is there a difference?
推荐答案
添加 :null =>false
表示这是数据库限制,即在任何情况下数据库都不允许空值.
Adding a :null => false
means that this is a database restriction, i.e. under no circumstance will the database allow a null value.
添加 presence: true
是模型级验证,因此将在对象插入数据库之前进行.在某些情况下您可能想要破坏这些验证(例如边缘情况或在您的规范中)您可以使用 :validates => 跳过验证.false
并且对象仍然会进入数据库,如果有空数据库限制,这不会发生.
Adding a presence: true
is a model level validation so will take place before the object is inserted into the database. There may be a case you want to break these validations (for example edge cases or in your specs) You can then skip validation using :validates => false
and the object will still go into the database, with a null DB restriction, this won't happen.
这篇关于在 Rails 模型/表中验证存在与 null false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!