【问题标题】:Rails 5 custom validateRails 5 自定义验证
【发布时间】:2017-09-26 20:19:18
【问题描述】:

我正在学习 Rails,我坚持使用这种自定义验证。我尝试了许多不同的方法来传递名为(:cpf) 的表单字段以进行验证,但均未成功。我也尝试过使用 ActiveModel::EachValidator,但我变得更加困惑。验证是使用模 11 的校验位。所以这就是我最终的结果。

controllers/drivers_controller.rb

  def new
    @driver = Driver.new
  end

  def create
    @driver = Driver.new(driver_params)
    if @driver.save
      flash[:success] = "Motorista cadastrado com sucesso!"
      redirect_to @driver
    else
      render 'new'
    end
  end

models/driver.rb

class Driver < ApplicationRecord

validate :checkcpf

private

  def checkcpf
    return false if cpf.nil?
    nulos = %w{12345678909 11111111111 22222222222 33333333333 44444444444 55555555555 66666666666 77777777777 88888888888 99999999999 00000000000}
    valor = cpf.scan /[0-9]/
    if valor.length == 11
      unless nulos.member?(valor.join)
        valor = valor.collect{|x| x.to_i}
        soma = 10*valor[0]+9*valor[1]+8*valor[2]+7*valor[3]+6*valor[4]+5*valor[5]+4*valor[6]+3*valor[7]+2*valor[8]
        soma = soma - (11 * (soma/11))
        resultado1 = (soma == 0 or soma == 1) ? 0 : 11 - soma
        if resultado1 == valor[9]
          soma = valor[0]*11+valor[1]*10+valor[2]*9+valor[3]*8+valor[4]*7+valor[5]*6+valor[6]*5+valor[7]*4+valor[8]*3+valor[9]*2
          soma = soma - (11 * (soma/11))
          resultado2 = (soma == 0 or soma == 1) ? 0 : 11 - soma
          return true if resultado2 == valor[10] # CPF VALIDO
        end
      end
    end
    return false # CPF INVALIDO
    errors.add(:cpf, "CPF INVÁLIDO")
  end
end

我想我错过了如何通过我的 cpf 字段进行验证。我收到错误消息或错过验证。

稍后当我对 Rails 有更好的理解时,我会尝试使用 ActiveModel::EachValidator。这就是我通常的做法,尝试让事情以我能理解的方式工作,然后重构 Rails 方式。

感谢您的帮助!谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby validation ruby-on-rails-5


    【解决方案1】:

    首先,无需从此方法返回truefalse,只需return - 您想从该方法返回,因为该字段有效或添加错误。我没有完全遵循您验证的逻辑,但无论结果如何,您总是return false # CPF INVALIDO 并且永远不会到达errors.add(:cpf, "CPF INVÁLIDO") 行。请记住 - 每当您从方法中return 时,您都会停止执行,因此您必须确保至少有一个执行路径可以到达该行,这会增加实际错误。

    【讨论】:

    • 感谢您的帮助。也许我会创建一个模块来测试这个方法并尝试验证它的真假......
    猜你喜欢
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多