“验证"和“验证"之间有什么区别?和“验证"? [英] What's the difference between "validate" and "validates"?

查看:30
本文介绍了“验证"和“验证"之间有什么区别?和“验证"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法向对象添加了验证:

I added a validation to an objects using:

validate :field, presence: true

我发现他们没有给出错误信息.我将它们更改为 validates 并收到错误消息.这张票是相关的.

I found they do not give error messages. I changed them to validates and got the error messages. This ticket is relevant.

我尝试使用 validates 添加自定义验证,但出现错误:

I tried to add a custom validation with validates and got an error:

You need to supply at least one validation

我将其更改为 validate,一切都按预期进行.

I changed it to validate, and everything went along as expected.

我的理解是将 validates 与普通验证一起使用,将 validate 与自定义验证一起使用.是对的吗?还有我应该知道的其他作品吗?有没有办法让第一个问题大声失败,而不仅仅是验证所有内容?

My understanding is to use validates with normal validations, and validate with custom ones. Is that right? Are there any other pieces I should know about? Is there any way to have the first problem fail loudly and not just validate everything?

推荐答案

validates 此方法是所有默认验证器和任何以Validator"结尾的自定义验证器类的快捷方式.请注意,可以通过在特定类中创建自定义验证器类(例如 PresenceValidator)来覆盖 Rails 默认验证器.

validates This method is a shortcut to all default validators and any custom validator classes ending in ‘Validator’. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as PresenceValidator.

validates :title, :body, :presence => true

validate,向类添加验证方法或块.当覆盖验证实例方法变得过于笨拙并且您正在寻找更具描述性的验证声明时,这很有用.

validate, Adds a validation method or block to the class. This is useful when overriding the validate instance method becomes too unwieldy and you’re looking for more descriptive declaration of your validations.

validate :must_be_friends

  def must_be_friends
    errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
  end

这篇关于“验证"和“验证"之间有什么区别?和“验证"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆