我想要一个像/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
类)。请使用第一种方式帮助我使用其他逻辑。
答案 0 :(得分:0)
我猜测category.name
未以unicode格式存储,因此它与xparams
中的内容不匹配。您需要确保两个值都是unicode,因此您可以正确匹配它们。
我认为这个类似的问题可以解决您的问题: