带有引擎路线参数的`link_to` [英] `link_to` with parameters for an Engine route
问题描述
(尽管这里讨论的是Blacklight引擎,但我认为问题实际上纯粹是关于Rails的.)
(While this discusses Blacklight engine, I believe the question is actually purely about Rails.)
是否继续从 scope
围绕mount
无效?(tl; dr :在浏览Rails源代码之后,使引擎路由服从与应用程序路由相同的:locale
范围.
Continuing my quest from scope
around mount
ineffective? (tl;dr: make the engine routes obey the same :locale
scope as application routes), after digging through Rails source.
当前,我具有以下设置:
Currently, I have this setup:
# config/routes.rb
Rails.application.routes.draw do
Blacklight::Engine.routes.default_scope = { path: "(:locale)", locale: /en|ja/ }
mount Blacklight::Engine => '/'
scope "(:locale)", locale: /en|ja/ do
# ...
end
end
这使路由正常工作.但是,我有此视图代码来生成指向当前页面的备用语言链接(由
This makes the routes work properly. However, I had this view code to generate the alternate-language links to the current page (guided by link_to the current page plus/merged with a param [duplicate]):
<div id="languages_nav_popup" class="navbar-inverse">
<% locales.each do |locale| %>
<% next if locale == I18n.locale %>
<%= link_to params.permit!.merge(locale: locale) do %>
<img src="<%= url_for "/img/flag/#{locale}.png" %>"/>
<% end %>
<% end %>
</div>
当当前页面是引擎路线时,link_to
失败.这是由于actionpack
中的这段代码:
That link_to
fails when the current page is an Engine route. This is due to this piece of code in actionpack
:
# lib/action_dispatch/journey/formatter.rb
# Skip this route unless a name has been provided or it is a
# standard Rails route since we can't determine whether an options
# hash passed to url_for matches a Rack application or a redirect.
next unless name || route.dispatcher?
使用我上面使用的link_to options, &block
语法,name
是nil
;引擎路线的dispatcher?
是false
. (如果我通过强行插入名称通过了此检查,则会得到类似.../assets?action=index&controller=saved_searches&locale=ja
的毫无意义的URL.)
With link_to options, &block
syntax that I use above, name
is nil
; and dispatcher?
is false
for an engine route. (If I pass that check by inserting a name by force, I get a nonsensical URL like .../assets?action=index&controller=saved_searches&locale=ja
).
我在这里感到绝望,几乎可以想到解决此问题的最佳方法是regexp.这种暴行有效:
I'm getting desperate here, almost to the point where I'm thinking the best way to deal with this is regexp. This atrocity works:
<%= link_to request.base_url + request.original_fullpath.sub(%r{(?<=/)#{I18n.locale}}, locale.to_s) do %
是否无法正确生成正确的URL?
Is there no way to generate the correct URL properly?
推荐答案
另一种完全hacky的解决方案是将引擎路由复制到本地route.rb并添加警告,该警告会在gem更新时触发,以检查它们的更改. :(
Another totally hacky solution is to copy the engine routes to your local routes.rb and add a warning that triggers on gem update to check them for changes. :(
这篇关于带有引擎路线参数的`link_to`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!