Rails:如何根据条件重定向到特定的控制器(索引)



我有一个可以生成"角色"的Ruby on Rails应用程序;电影中的演员;这个想法是,如果用户查看电影详细信息页面,他们可以单击"添加角色",如果他们查看演员详细信息页面,也可以这样做。一旦角色生成,我想重定向到他们来自哪里-电影详细页面或演员详细页面…所以在控制器的"创建"中和";update"方法时,redirect_to应该是movie_path(id)或actor_path(id)。我如何保持"本源"?持久性,即我如何记住用户是来自电影细节还是来自演员细节(分别是id)?

我会设置单独的嵌套路由,只使用继承、混合和部分来避免重复:

resources :movies do
resources :roles, module: :movies, only: :create
end
resources :actors do
resources :roles, module: :actors, only: :create
end
class RolesController < ApplicationController 
before_action :set_parent
def create
@role = @parent.roles.create(role_params)
if @role.save 
redirect_to @parent
else
render :new
end
end
private 
# guesses the name based on the module nesting
# assumes that you are using Rails 6+ 
# see https://stackoverflow.com/questions/133357/how-do-you-find-the-namespace-module-name-programmatically-in-ruby-on-rails
def parent_class
module_parent.name.singularize.constantize
end
def set_parent
parent_class.find(param_key)
end
def param_key
parent_class.model_name.param_key + "_id"
end
def role_params
params.require(:role)
.permit(:foo, :bar, :baz)
end
end
module Movies
class RolesController < ::RolesController
end
end
module Actors
class RolesController < ::RolesController
end
end
# roles/_form.html.erb
<%= form_with(model: [parent, role]) do |form| %>
# ...
<% end %>