【问题标题】:What is the best way to translate slugs in Rails routes在 Rails 路线中翻译 slug 的最佳方法是什么
【发布时间】:2012-02-10 19:20:22
【问题描述】:

我正在尝试在 Rails3.1 应用程序中实现路线的完全国际化。我已经在使用 Francesc Pla 的 rails-translate-routes 来本地化路线操作和资源。最后一步是能够为我的一些模型翻译 slug。

待翻译路线:

http://myhost.com/products/pharmacy --> http://myhost.com/productos/farmacia

我有一个表单的嵌套路由

# routes.rb
match 'products/:category_slug' => "products#index"

我有一个带有实例 #<Category id: 1, slug: "pharmacy"> 的模型类别,我在 ProductsController 中使用 find_by_slug 类别。

关于如何翻译路线的:category_slug 部分有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails-3 internationalization routes translation


    【解决方案1】:

    据我所知,只要您使用I18n 正确命名空间,您就可以直接从控制器调用翻译助手。

    因此您的 ProductsController 可能包含以下内容:

    class ProductsController < ApplicationController
      def index
        i18n_slug = I18n.t("locale.category.#{params[:category_slug]}")
        @category = Category.find_by_slug(i18n_slug)
      end
    end
    

    您可能应该告知自己将参数直接传递到翻译引擎的潜在安全风险,尽管我不知道有任何风险。你也可以考虑 如果将在多个控制器操作中使用,则将其移动到前置过滤器或应用程序控制器中。

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2011-05-15
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多