我有一個 Ruby on Rails 應用程式,可以為電影中的演員生成“角色”;這個想法是,如果用戶查看電影詳細資訊頁面,他們可以單擊“添加角色”,如果他們查看演員詳細資訊頁面,則同樣如此。一旦角色生成,我想重定向回他們來自哪里 - 電影詳細資訊頁面或演員詳細資訊頁面......所以在控制器的“創建”和“更新”方法中,redirect_to 應該是 movie_path( id) 或 actor_path(id)。我如何保持“來源”的持久性,即我如何記住用戶是來自電影細節還是來自演員細節(分別是 id)?
uj5u.com熱心網友回復:
我會設定單獨的嵌套路由,只使用繼承、混合和部分來避免重復:
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 %>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338835.html
標籤:红宝石轨道
