我正在尝试使用valid?
方法在模型中进行自定义验证。我需要运行此模型的所有验证,密码除外。
像这样的东西:
@resource = SalesPartner.new(permitted_params.merge(parent: current_sales_partner))
respond_to do |format|
if @resource.valid?(except: :password)
@resource.generate_authentication_token
SalesPartnerMailer.mail_new_sales_partner(@resource.email,
{ auth_token: @resource.authentication_token, id: @resource.id, level: @resource.level }
).deliver
flash[:success] = "#{@resource.level} criado com sucesso."
format.html { render "#{@path}/index" }
else
logger.log_and_alert_save_error(@resource, flash, "Ocorreu um erro ao salvar.")
format.html { render "#{@path}/new" }
end
end
那可能吗?
感谢大家!
最佳答案
这里的任何方式都是您可以借助上下文进行的一种方式。假设您有一个User
模型,并且想验证一些字段。
validates_presence_of :name,: email, on: :special_context
validates_presence_of :name,:email, :password
使用上面的2行,您现在可以像下面这样@user.valid?(:special_context)
上面的代码将验证name
和email
字段。如果你现在写,@user.valid?
在您编写时,这将对name
,email
和password
字段执行在线状态验证。阅读
valid?(context = nil)
以了解上下文。Runs all the validations within the specified context. If the argument is
false
(default isnil
), the context is set to:create
ifnew_record?
is true, and to:update
if it is not.Validations with no
:on
option will run no matter the context. Validations with some:on
option will only run in the specified context.
也可以将此documentation作为官方示例进行检查。
关于ruby-on-rails - 验证除Rails中的一个以外的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078919/