简体   繁体   English

如何在Ruby on rails上获取验证错误消息?

[英]How to get validations error messages in Ruby on rails?

I'm currently learning Ruby on rails with OpenClassrooms, and they are using that piece of code : 我目前正在使用OpenClassrooms学习Ruby on rails,他们正在使用这段代码:

validates :name, presence: {
    message: "Give a name"
}

When I try to create an object without the name, I'm not getting any error. 当我尝试创建一个没有名称的对象时,我没有收到任何错误。 For example : 例如 :

me = Person.new name:""
me.errors.to_hash
=> {}

With the same example (just not the same classes), OpenClassrooms get an error and I don't know why I don't get any error 使用相同的示例(只是不同的类),OpenClassrooms收到错误,我不知道为什么我没有得到任何错误

Errors are added to an object after validation. 验证后将错误添加到对象。 When you call new , you're not validating anything, so the object has no errors. 当你调用new ,你没有验证任何东西,所以对象没有错误。

If you try and save it and then check the errors, you will get what you're looking for: 如果您尝试保存它然后检查错误,您将获得您正在寻找的内容:

me = Person.new name:""
me.errors.to_hash
=> {}
me = Person.new name:""
me.save
=> false
me.errors.to_hash
=> ActiveModel::Errors...

Call me.validate before checking the error object. 在检查错误对象之前调用me.validate You can also call #valid? 你也可以打电话给#valid? .

me = Person.new name: ""
me.validate
me.errors.to_hash
=> { ... }

All saving methods call this #validate method internally, such as #save and #save! 所有保存方法都在内部调用此#validate方法,例如#save#save! .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM