以下是我找到的选项:
request.referrer
似乎没有以您描述的方式访问控制器类/操作的内置方式,但您可以访问发起 Turbo 请求的页面的 URL(groups_controller#show ) 通过request.referrer。这将是页面的完全限定 URL,例如 http://localhost:3000/groups/1/show。
- 使用查询参数
这需要更改查看代码(您必须将查询参数添加到需要此功能的所有链接),但它允许您传递控制器/操作名称以及您想要的任何其他任意数据。
例子:
在 application_controller.rb 中:
# define a method to capture the information you wish to access during your Turbo stream request
def current_route_info
{
path: current_path,
controller: params[:controller],
action: params[:action]
}
end
在此示例中无需触摸组控制器。
在show.html.erb(提交Turbo请求的页面)
<%= form_with url: turbo_view_path(info: current_route_info) do %>
...
<% end %>
OR
<%= link_to turbo_view_path(info: current_route_info) do %>
...
<% end %>
OR
<!-- you could also manually build the URL & encode the query params if you need to avoid URL helpers-->
<turbo-frame id="" src=chats_partial_path(info: current_route_info)>
...
<turbo-frame>
聊天部分控制器(处理 Turbo 请求)
def turbo_view_method
params[:info]
# => info as defined in current_route_info
end
- 使用
flash
我刚刚了解了您可以将flash 用于这种跨请求扩展的功能的多种方式。这比使用查询参数的工作量少,主要是因为您不需要调整视图代码。
例子:
组控制器(呈现显示视图,提交 Turbo 请求)
def show
# stick the current controller and action params into flash
# again, you can add any other arbitrary (primitive) data you'd like
flash[:referrer] = params.slice(:controller, :action)
...
...
end
聊天部分控制器(处理 Turbo 请求)
def chats_turbo_method
flash[:referrer]
# => { controller: "some_controller", action: "show" }
# NOTE: flash will retain this :referrer key for exactly 1 further request.
# If you require this info for multiple Turbo requests,
# you must add:
flash.keep(:referrer)
# and you will have access to flash[:referrer] for as many Turbo requests as you want to make from group#show
end