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

标签 ruby-on-rails validation

我正在尝试使用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/

相关文章:

ruby-on-rails - 使用 AJAX 更新 Javascript 变量

javascript - 使用 Jquery 和 Ajax 根据组合框中选定的值自动填充表单

javascript - jQuery 验证插件 : Show your error message/image in next column(td) of table

java - 在单元测试中调用 Spring Repository.save() 时未触发 Hibernate Validator

ruby-on-rails - 电子邮件中的 PDF 附件称为 'Noname'

ruby-on-rails - 官方指南中的铁路路线错误

html - 导航栏中的链接是垂直列出的,而不是在 Rails 元素中水平列出的

java - Java 中用于验证用户名的正则表达式

javascript - 检查条件后表单验证不发出警报

javascript - jQuery 验证普通按钮上的表单(不提交)