首页 > 解决方案 > Rails 多步表单,带有一个没有 gem 的控制器

问题描述

我有一个应用程序,其中一个注册步骤是填写调查。该调查有两个步骤,在提交step_1用户答案后应重定向到step_2(每个步骤都会创建与用户关联的新数据库记录 AppropriatenessTestResult - current_user.appropriateness_test_results.new)。

我目前的方法使用控制器继承,但我想知道在一个控制器而不是三个控制器中是否有更好的方法?

基本控制器:

class AppropriatenessTestBaseController < SignupBaseController
  before_action :authenticate_user!

  def new
    authorize current_user, policy_class: authentication_policy

    @appropriateness_test_result = AppropriatenessTestResult.new
  end

  def create
    authorize current_user, policy_class: authentication_policy

    @appropriateness_test_result = current_user.appropriateness_test_results.new(
      step: current_step,
      #other db fields
     ).call

    if @appropriateness_test_result.save && AppropriatenessTestResults::Update.new(current_user).call
      redirect_to next_step_path
    else
      render :new, status: :unprocessable_entity
    end
  end

step_one 控制器:

module AppropriatenessTest
  class StepOnesController < AppropriatenessTestBaseController
    private

    def current_step
      1
    end

    def authentication_policy
      AppropriatenessTestStepOnePolicy
    end

    def next_step_path
      new_appropriateness_test_step_two_path
    end
  end
end

step_two 控制器

module AppropriatenessTest
  class StepTwosController < AppropriatenessTestBaseController
    private

    def current_step
      2
    end

    def authentication_policy
      AppropriatenessTestStepTwoPolicy
    end

    def next_step_path
      new_users_identity_check_path
    end
  end
end

路线:

  namespace :appropriateness_test do
    resource :step_one, only: %i[new create]
    resource :step_two, only: %i[new create]
  end

我不想使用任何宝石,例如wickedor third-party

标签: ruby-on-rails

解决方案


推荐阅读