I'm learning RoR at the moment, and I think I must be misunderstanding something.
我正在学习RoR,我想我一定是在误解。
I have an ActiveRecord class call User, with simple validations on :name and :email such as presence: true, length: { maximum: 15 }, etc. I thought I'd check the validations in the console. I go into rails console (development env), and create a new instance with a name that is too long, such as user_instance = User.new (name:"aaaaabbbbbcccccddddd", email:"").
我有一个ActiveRecord类调用User,其上有简单的验证:name和:email,如presence:true,length:{maximum:15}等等。我以为我会在控制台中检查验证。我进入rails console(开发环境),并创建一个名称太长的新实例,例如user_instance = User.new(name:“aaaaabbbbbcccccddddd”,email:“”)。
The validation doesn't throw up any errors. When I try user_instance.save, the record won't write to the DB, so it's obviously working fine at that stage. What am I doing wrong?
验证不会引发任何错误。当我尝试user_instance.save时,记录不会写入DB,因此在该阶段显然工作正常。我究竟做错了什么?
2 个解决方案
#1
13
When you want to get an exception raised on record saving, use save!
instead of save
(same with update
/update!
, create/create!
).
如果要在保存记录时获得异常,请使用save!而不是保存(与更新/更新相同!,创建/创建!)。
With save
you won't have an exception raised if there are validation errors, it will just return false
. You can also check if there are errors on an instance with user_instance.valid?
and get the errors with user_instance.errors
.
使用save,如果存在验证错误,则不会引发异常,它将返回false。您还可以使用user_instance.valid检查实例上是否存在错误?并使用user_instance.errors获取错误。
See When Does Validation Happen?.
查看验证何时发生?
#2
5
the validation won't throw errors if you try to set invalid data on your model, however the save will fail.
如果您尝试在模型上设置无效数据,验证将不会抛出错误,但保存将失败。
if you wanna check out if the validation is working correctly, just check user.valid? and it should return false
如果你想检查验证是否正常工作,只需检查user.valid?它应该返回false
after calling valid?, you can check user.errors for the specific errors set on your model.
在调用有效?后,您可以检查user.errors以查找模型上设置的特定错误。
#1
13
When you want to get an exception raised on record saving, use save!
instead of save
(same with update
/update!
, create/create!
).
如果要在保存记录时获得异常,请使用save!而不是保存(与更新/更新相同!,创建/创建!)。
With save
you won't have an exception raised if there are validation errors, it will just return false
. You can also check if there are errors on an instance with user_instance.valid?
and get the errors with user_instance.errors
.
使用save,如果存在验证错误,则不会引发异常,它将返回false。您还可以使用user_instance.valid检查实例上是否存在错误?并使用user_instance.errors获取错误。
See When Does Validation Happen?.
查看验证何时发生?
#2
5
the validation won't throw errors if you try to set invalid data on your model, however the save will fail.
如果您尝试在模型上设置无效数据,验证将不会抛出错误,但保存将失败。
if you wanna check out if the validation is working correctly, just check user.valid? and it should return false
如果你想检查验证是否正常工作,只需检查user.valid?它应该返回false
after calling valid?, you can check user.errors for the specific errors set on your model.
在调用有效?后,您可以检查user.errors以查找模型上设置的特定错误。