【问题标题】:Finding the current URL or "main" controller from within a Turbo Frame in Rails在 Rails 的 Turbo Frame 中查找当前 URL 或“主”控制器
【发布时间】:2021-07-12 08:50:17
【问题描述】:

我的页面上有一个 Turbo Frame,它使用src 属性加载/chats/。在这个框架内,我希望能够知道 ma​​in 页面是否使用了 groups 控制器的 show 操作,即页面的 URL 位于 /groups/group_name

使用 current_page?(controller: 'groups', action: 'show') 会返回 false,因为它认为自己就像在 chats 控制器中一样。我该如何解决这个问题?

【问题讨论】:

  • 我从来不需要尝试这个,但是你能在src属性中添加查询参数吗?

标签: ruby-on-rails ruby-on-rails-5 hotwire-rails turbo-frames


【解决方案1】:

以下是我找到的选项:

  1. request.referrer

似乎没有以您描述的方式访问控制器类/操作的内置方式,但您可以访问发起 Turbo 请求的页面的 URL(groups_controller#show ) 通过request.referrer。这将是页面的完全限定 URL,例如 http://localhost:3000/groups/1/show

  1. 使用查询参数

这需要更改查看代码(您必须将查询参数添加到需要此功能的所有链接),但它允许您传递控制器/操作名称以及您想要的任何其他任意数据。

例子:

在 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
  1. 使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多