没有与日语相匹配的路线

时间:2013-12-23 14:59:28

标签: ruby-on-rails ruby ruby-on-rails-4 routes constraints

我想要一个像/posts/category1/category2/这样的网址,所以我在routes.rb中写了以下内容:

class CategoryConstraints
  def self.matches?(request)
    xparams = request.params[:k].split("/")
    xparams & Category.pluck(:name) == xparams
  end
end

RailsApp::Application.routes.draw do
  get "/posts(/:k)" => "posts#index", constraints: CategoryConstraints
end

它与罗马字类别名称完美配合,但当类别名称是日语时,例如当我访问/posts/新規開発/时,会引发以下错误:

No route matches [GET] "/posts/%E6%96%B0%E8%A6%8F%E9%96%8B%E7%99%BA/

我认为这是因为日语字符已转换为Unicode,因此route无效。如果我更改为constraints: {k: /.*/},一切正常,但我无法像第一种方式一样处理constraints中的逻辑(routes返回false而不访问CategoryConstraints类)。请使用第一种方式帮助我使用其他逻辑。

1 个答案:

答案 0 :(得分:0)

我猜测category.name未以unicode格式存储,因此它与xparams中的内容不匹配。您需要确保两个值都是unicode,因此您可以正确匹配它们。

我认为这个类似的问题可以解决您的问题:

How to convert text to unicode in Rails?