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

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



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?


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/

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