1

I have registration that consist of 2 steps. In the first one, the new user will set up his name, email and password. Then he clicks on the "Sign Up" button and is redirected on the page where is the second part of the registration form (approx 5-7 fields).

I have set up validation rules on all inputs (7-10 fields). The problem is, when I fill out the first part of the form and then I click on the Sign Up button, I see validation errors, because the fields from the second part of the form are not valid.

How to avoid this behavior?

Thank you

4

1 回答 1

1

您可以定义一个虚拟属性,该属性将用于确定在哪个步骤验证哪些属性,然后使用该属性的值with_options在每个步骤验证必填字段。

如下所示:

在您的模型中:

class MyModal < ActiveRecord::Base
  attr_accessor :validate_step

  with_options if: :validate_step_one? do |o|
    o.validates :name, presence: true 
    o.validates :email, presence: true 
    o.validates :password, presence: true 
  end

  with_options if: :validate_step_two? do |o|
    ...
  end

  private:

  def validate_step_one?
    self.validate_step == 'validate_first_step'
  end

  def validate_step_two?
    self.validate_step == 'validate_second_step'
  end
end

然后在你的控制器中:

class MyRegistrationController < ApplicationController
  def show
    case step
      when :first_step
        user.validate_step = 'validate_first_step'
      when :second_step
        user.validate_step = 'validate_second_step'
    end
  end
end

在您的控制器中,在您构建对象的操作中,您需要分配validate_first_stepvalidate_second_step基于向导中的当前步骤。

请注意,我使用的值和名称不是很具有描述性/意义,您会更好地知道如何命名它们:)

于 2013-09-04T14:53:37.623 回答