【发布时间】: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