ruby-on-rails - 将参数传递给 redirect_to
问题描述
我有一个控制器来在系统上注册新员工,在这个控制器中我需要验证以确保插入的电子邮件和 CPF(巴西文档)都是唯一的并且尚未注册。我正在尝试使用 redirect_to 返回表单:
def create
@model = Employee.new(employee_params)
@model.cpf_plain = employee_params[:cpf].gsub('-', '').gsub('.', '')
@model.activated = true
if Employee.where(email: @model.email).first.present? || Employee.where(cpf_plain: @model.cpf_plain).present?
redirect_to new_employee_url(employee: employee_params), notice: 'Já existe um Otto com este email ou CPF'
return
end
if @model.save
@model.generateTempPass
redirect_to employees_url, notice: 'Otto criado com sucesso.'
else
redirect_to new_employee_url(employee: employee_params),
notice: 'Não foi possível salvar este Otto no momento, tente novamente mais tarde.'
end
end
但我不知道如何返回保留已填写字段的表单。我尝试使用渲染而不是 return_to:
if Employee.where(email: @model.email).first.present? || Employee.where(cpf_plain: @model.cpf_plain).present?
render create, notice: 'Já existe um Otto com este email ou CPF'
return
end
但由于某种原因,我进入了一个无限循环,控制器不断地反复验证电子邮件和 CPF。
解决方案
我认为丹的评论是正确的,你需要渲染新的,而不是创造。
if Employee.where(email: @model.email).any? || Employee.where(cpf_plain: @model.cpf_plain).present?
render :new, notice: 'Já existe um Otto com este email ou CPF' and return
end
(我更改了“first.present?”并将渲染也缩短为一行)
推荐阅读
- python-3.x - 显式 __init__ python
- css - 如何循环一组动画,即每行在css动画中弹跳一次?
- spring-boot - ConditionalOnExpression 无法将配置属性与枚举类型进行比较,作为字符串工作
- c# - NewtonSoft 不正确的反序列化
- selenium - 从下拉框中选择 - selenium
- c++ - 在 Windows 上使用 C++ 中的 Select 函数进行轮询
- linq - 将字符串转换为 linq 条件实体框架核心
- javascript - 如何允许 Angular 5 Web 应用程序在同一浏览器的多个选项卡中打开
- c++ - SDL2 | 包装类访问冲突
- javascript - onclick 和 $("#abc").click(function(){}) 的优先级,哪个优先级更高?