Ruby on Rails 7多步骤表单与多模型逻辑



我目前正在努力建立一个多步骤的形式,其中每一步创建一个模型实例。

在这种情况下,我有3个模型:

  1. UserPlan
  2. GameDashboard

既然关联是这样的:

一个user有一个user_planconnection属于user_plangame_dashboard属于connection

我想创建一个向导,允许current_user创建一个game_dashboard通过一个多步骤的形式,他也创建连接和user_plan实例。

为此,我查看了Wicked gem,并开始从game_dashboard创建逻辑(这是最后一个)。当我不得不面对生成表单时,我觉得也许从底部开始并不是更好的解决方案。

这就是我来这里寻求帮助的原因:

实现这个向导的更好的方法是什么?从底部开始(game_dashboard)或开始从顶部(use_plan)?

因为我没有要求帮助的代码,我没有写任何控制器或模型的逻辑,以防它会对别人有帮助,我会把它!

Thanks a lot


编辑因为我需要一次只允许一个进程,但允许多个进程,为了避免参数值,我决定创建一个新的模型,称为"onboarding"我在这里处理步骤状态,每次检查步骤

最简单的方法是依赖Rails的标准MVC模式。

只需使用createupdate控制器方法链接到下一个模型的表单(而不是showindex视图)

class UserPlansController < ApplicationController
...
def create
if @user_plan = UserPlan.create(user_plan_params)
# the next step in the form wizard process:
redirect_to new_connection_path(user_id: current_user, user_plan_id: @user_plan.reload.id)
else
@user_plan = UserPlan.new(user: current_user)
render :new
end    
end
...
# something similar for #update action
end

对于路由,您有两个选项:

你可以嵌套所有东西:

# routes.rb
resources :user do
resources :user_plan do
resources :connection do
resources : game_dashboard
end
end
end

职业:

这将使在控制器中设置关联更容易,因为所有的路由都有你需要的。例如:

/users/:user_id/user_plans/:user_plan_id/connections/:connection_id/game_dashboards/:game_dashboard_id

反对:

你的路由和链接帮助将是非常长和密集的"底部"。例如

game_dashboard_connection_user_plan_user_path(:user_id, :user_plan_id, :connection_id, :game_dashboard)

你可以手动链接你的向导步骤在一起

职业:

url和helper并没有那么疯狂。例如

new_connection_path(user_plan_id: @user_plan.id)

使用一个有意义的URL变量:user_plan_id=1,您可以查找上游的所有内容。例如:

@user_plan = UserPlan.find(params['user_plan_id'])
@user = @user_plan.user

反对:

(没有太多的"因为你可能最终还是会这样做)

如果需要显示"parent"记录,您必须首先在控制器中执行模型查找:

class GameDashboardController < ApplicationController
# e.g. URL: /game_dashboards/new?connection_id=1
def new
@connection = Connection.find(params['connection_id'])
@user_plan = @connection.user_plan
@user = @user_plan.user
@game_dashboard = GameDashboard.new(connection: @connection)
end
end

最新更新