就我个人而言,我会让模型管理它自己的验证,并将管理每个步骤验证的逻辑移至该模型。
现在,这可能不是最优雅的方法,但它很有效,并且不会使代码过于混乱。
Add a step
模型的瞬态属性。
attr_accessor :step
将以下方法添加到模型中以检查步骤是否正确:
def on_step(step_number)
step == step_number or step.nil?
end
的原因step.nil?
- 这样做的优点是,如果您想在该模型上使用验证而不使用步骤,只需不要为模型上的步骤分配值,并且该方法将允许返回 true,从而始终执行验证。
将验证更改为仅在正确步骤时进行处理,或者在不使用步骤时绕过
validates :first_name, if: "on_step 1", presence: true
validates :last_name, if: "on_step 1", presence:true
validates :email, if: "on_step 1", presence:true
validates :password, if: "on_step 2", presence:true
validates :phone, if: "on_step 2", format:{ with: TEL_REGEX }, allow_blank: false
validates :address, if: "on_step 2", presence:true
当然,不要忘记设置模型的当前步骤,例如通过将其硬编码在表单的隐藏字段中(如果为每个步骤渲染单独的表单)并更改参数以接收它。