有没有一种方法来验证对一个ActiveRecord特定属性不首先实例化对象? [英] Is there a way to validate a specific attribute on an ActiveRecord without instantiating an object first?

查看:105
本文介绍了有没有一种方法来验证对一个ActiveRecord特定属性不首先实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个用户模式,我只需要验证登录(验证通过AJAX表单时,它可以发生),如果我使用的用户模型中定义相同的模型验证,而无需实际实例化将是巨大的用户实例。

For example, if I have a user model and I need to validate login only (which can happen when validating a form via ajax), it would be great if I use the same model validations defined in the User model without actually instantiating a User instance.

因此​​,在控制器我能写code像

So in the controller I'd be able to write code like

User.valid_attribute?(:login, "login value")

反正我能做到这一点?

Is there anyway I can do this?

推荐答案

由于验证的情况下运行(和他们使用错误的实例作为容器的错误信息属性),你不能使用它们,而无需对象实例化。说了这么多,你可以隐藏这个需要的行为放到一个类方法:

Since validations operate on instances (and they use the errors attribute of an instance as a container for error messages), you can't use them without having the object instantiated. Having said that, you can hide this needed behaviour into a class method:

class User < ActiveRecord::Base
  def self.valid_attribute?(attr, value)
    mock = self.new(attr => value)
    unless mock.valid?
      return mock.errors.has_key?(attr)
    end
    true
  end
end

现在,你可以叫

User.valid_attribute?(:login, "login value")

就像你意。

(理想情况下,你会直接包括类方法进入的ActiveRecord :: Base的,因此将提供给每一个模型。)

(Ideally, you'd include that class method directly into the ActiveRecord::Base so it would be available to every model.)

这篇关于有没有一种方法来验证对一个ActiveRecord特定属性不首先实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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