gpt4 book ai didi

ruby-on-rails - 验证除Rails中的一个以外的所有属性

转载 作者:行者123 更新时间:2023-12-04 05:44:10 25 4
gpt4 key购买 nike

我正在尝试使用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)
上面的代码将验证 nameemail字段。如果你现在写,
@user.valid?
在您编写时,这将对 nameemailpassword字段执行在线状态验证。
阅读 valid?(context = nil) 以了解上下文。

Runs all the validations within the specified context. If the argument is false (default is nil), the context is set to :create if new_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com