首页 > 解决方案 > 将参数传递给 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。

标签: ruby-on-rails

解决方案


我认为丹的评论是正确的,你需要渲染新的,而不是创造。

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?”并将渲染也缩短为一行)


推荐阅读