[英]How do i run validates_presence_of on an instance in rails?
I would like to do the following from a library class? 我想从库类中执行以下操作?
class LibClass
def create_user(provider)
user = User.new
if provider == "facebook"
user.validates_presence_of :email
else
# dont validate presence of email
end
end
end
I am aware that I can do a self.validates_presence_of :email inside the User class, but I am in the library class and am not sure how to do this? 我知道可以在User类中执行self.validates_presence_of:email,但是我在类库中,不确定如何执行此操作?
In your User
model, you can create an accessor to toggle the validation on or off. 在您的User
模型中,您可以创建访问器以打开或关闭验证。
class User < ActiveRecord::Base
attr_accessor :validate_email
def validate_email?; validate_email == true; end
validates_presenece_of :email, :if => validate_email?
end
You can turn the validation on by setting user.validate_email = true
: 您可以通过设置user.validate_email = true
来打开验证:
def create_user(provider)
user = User.new
if provider == "facebook"
user.validate_email = true
else
user.validate_email = false
end
end
To actually get the validations to run, you can call user.valid?
要实际运行验证,可以调用user.valid?
and the hash user.errors
will be populated with any validation errors. 哈希user.errors
将填充任何验证错误。
validates_presence_of is a class method, not an instance method. validates_presence_of是一个类方法,而不是实例方法。 In order to do what you want you'll have to do this: 为了执行您想要的操作,您必须执行以下操作:
user.class_eval {validates_presence_of :email }
but the validation will be set on the class, and will be on for all your users. 但验证将在课程上进行,并且将对所有用户进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.