在 Rails 中调用自定义验证方法 [英] calling custom validation methods in Rails

查看:51
本文介绍了在 Rails 中调用自定义验证方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将 Rails 升级到 2.3.4,我通过验证注意到了这一点:假设我有一个简单的模型公司,它有一个名字.没什么.我想运行我自己的验证:

I just upgraded my rails to 2.3.4 and I noticed this with validations: Lets say I have a simple model Company which has a name. nothing to it. I want to run my own validation:

class Company < ActiveRecord::Base

  validate :something


  def something
    false
  end

end

在这种情况下,保存模型实际上是有效的.如果我覆盖 validate() 并返回 false,也会发生同样的事情.我在一个更复杂的模型中注意到了这一点,其中我的验证返回 false,但对象仍在保存……我在一个基本上为空的模型中进行了尝试,并应用了相同的方法.有没有我缺少的新练习?在我的一些旧 Rails 代码中,情况似乎并非如此.

saving the model actually works in this case. The same thing happens if i override validate() and return false. I noticed this in a more complex model where my validation was returning false, but the object was still saving...I tried it out in an essentially empty model and the same thing applied. Is there a new practice I am missing? This doesn't seem to be the case in some of my older rails code.

推荐答案

当您使用 validate 方法时,将执行您的验证.但是 rails 不依赖于返回值.

Your validations are executed when you use the validate method. However rails doesn't relies on the returned value.

它取决于是否存在验证错误.因此,当您的模型未通过验证时,您应该添加错误.

It relies on if there are validations errors or not. So you should add errors when your model doesn't validates.

def something
    errors.add(:field, 'error message')
end

或者,如果错误与字段无关:

Or, if the error is not related to a field :

def something
    errors.add(:base, 'error message')
end

那么你的模型将不会被保存,因为有错误.

Then your model won't be saved because there are errors.

这篇关于在 Rails 中调用自定义验证方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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