什么是在Rails路由中翻译Slug的最佳方法?

5
我正在尝试在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,其中有一个实例 #<Category id: 1, slug: "pharmacy">,我在 ProductsController 中使用 find_by_slug 查找类别。
有什么想法如何翻译路由中的 :category_slug 部分吗?
1个回答

0
据我所知,只要在控制器中正确使用命名空间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

你应该了解将参数直接传递到翻译引擎可能存在的安全风险,尽管我不知道有任何问题。如果它将在多个控制器操作中使用,你还可以考虑将其移动到 before 过滤器或应用程序控制器中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接