启动 Rails I18n 和 url 助手似乎会混淆 locale 和 id

2024-01-07

我刚刚开始尝试更新我们的 Rails 3.2 应用程序以实现国际化。我在路线中有一个可选范围,例如

范围“(:locale)”,区域设置:/en|es|zh-HK|de|fr/ do

正如所描述的http://guides.rubyonrails.org/i18n.html http://guides.rubyonrails.org/i18n.html.

我的网址助手喜欢

watch_url(@watch)

收到表单错误

没有路由匹配 {:action=>"show", :controller=>"watches", :locale=>#“”,“收件人” =>"", "attributes"=>""}, 状态: {}, 隐藏: false, 注释: "">}

关于为什么会发生这种情况以及如何解决它有什么想法吗?

Thanks!

EDIT:

在我的应用程序控制器中,我有

  before_filter :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

以及手表控制器的路线(这是一个已有 8 年历史的专有应用程序,我们有 100 多个控制器:(,所以我不会包括所有路线)...

$ rake routes | grep watch
                              watches GET    (/:locale)/watches(.:format)                                                         watches#index  {:locale=>/en|es|zh-HK|de|fr/}
                                      POST   (/:locale)/watches(.:format)                                                         watches#create {:locale=>/en|es|zh-HK|de|fr/}
                            new_watch GET    (/:locale)/watches/new(.:format)                                                     watches#new {:locale=>/en|es|zh-HK|de|fr/}
                           edit_watch GET    (/:locale)/watches/:id/edit(.:format)                                                watches#edit {:locale=>/en|es|zh-HK|de|fr/}
                                watch GET    (/:locale)/watches/:id(.:format)                                                     watches#show {:locale=>/en|es|zh-HK|de|fr/}
                                      PUT    (/:locale)/watches/:id(.:format)                                                     watches#update {:locale=>/en|es|zh-HK|de|fr/}
                                      DELETE (/:locale)/watches/:id(.:format)                                                     watches#destroy {:locale=>/en|es|zh-HK|de|fr/}

我认为显示方法不相关。错误发生在 url 帮助程序中,并且流程永远不会到达显示代码。


你需要给 url 助手一个locale option http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-url-params以及为了使其正确通过:

watch_url(@watch, locale: I18n.locale)

如果这有点烦人,你可以覆盖 Railsurl_options方法总是给每个请求一个:locale选项,因此您永远不必在任何视图中指定它(一些指南,包括上面的 Rails 指南链接,比如覆盖default_url_options方法,但这对我不起作用......):

应用程序/控制器/application_controller.rb

class ApplicationController < ActionController::Base
  # Every helper method dependent on url_for (e.g. helpers for named
  # routes like root_path or root_url, resource routes like books_path
  # or books_url, etc.) will now automatically include the locale in
  # the query string,
  def url_options
    { locale: I18n.locale }.merge(super)
  end

  # ...
end

应用程序/视图/your_view

# locale not needed explicitly as it's set in the controller
<%= link_to watch_url(@watch) %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

启动 Rails I18n 和 url 助手似乎会混淆 locale 和 id 的相关文章

随机推荐