RubyonRails路线:如何有或没有参数化路线 - Ruby on Rails Routes: How to have OR in your routes without parameterizing it

- 此内容更新于:2015-12-20
主题:

所以我有一个路线:有时我将得到的url格式/:param1+:param2。考虑到这一点,我试着:但问题是我认为括号是可选的,因为这是Rails的路线是如何工作的。我似乎不能使用regex除非分配一个变量。如果我有一个变量:符号分配(-|+)的约束,那么它的工作原理。但是我不想符号是一个变量,因为我必须记得符号作为参数当我构建路径和做其他的事情。有更好的方法吗?

原文:

So I have a route:

get '/:param1-:param2', param1: /some_constraint/, param2: /some_constraint/

Sometimes I would get the the url in the format /:param1+:param2. To account for this, I tried:

get '/:param1(-|+):param2', param1: /some_constraint/, param2: /some_constraint/

But the problem is I think the parenthesis makes it optional because that's how Rails routes work. I seems I can't use regex unless a variable is assignes to it. If I have a variable :symbol assigned to the (-|+) constraint, then it works. But I don't want the symbol to be a variable because then I would have to remember symbol as a parameter when I build path and do other things. Is there a better way to do this?

解决方案:
记得路线。rb文件是一个Ruby文件,所以你可以循环:缺乏一个更好的名字,但你可以找到更多的上下文,你在做什么。
原文:

Remember the routes.rb file is a Ruby file, so you could loop:

%w(+ -).each |symbol|
  get "/:param1#{symbol}:param2", param1: /some_constraint/, param2: /some_constraint/
end

symbol for the lack of a better name, but you can find something more in context to what you are doing.