문제

I have a method that generates a random url ending and a get path that looks like

/path/var1/var2

The only problem is that some of those generated values for var2 have a "/" in them. So if var 2 is "h4rd/erw" rails reads it as

/path/var1/h4rd/erw or

/path/var1/var2/var3

rails thinks that this is another parameter of the route and i keep get the error No route matches. I have thought of setting up the generated value for var2 to not include "/"s or possibly putting a wildcard in the route if that's possible like /path/var1/*. What would be the best solution for this?

도움이 되었습니까?

해결책

You can use route globbing:

get '/path/var1/*var2', to: 'controller#action'

Let's say the request went to /path/var1/h4rd/erw. Then in the controller action, the value of params[:var2] would be h4rd/erw.

다른 팁

I would make sure that the values are always escaped.

string = "my/string"
=> "my/string"
CGI.escape(string)
=> "my%2Fstring"

So your url will be like

/path/var1/h4rd%2Ferw

and it will go to the right controller with the right variables set.

Rails will automatically unescape the values of parameters in the controller "params" variable, so by the time you're dealing with the value in the controller the slash will be back in the string.

The only remaining question is when to do the escaping. If you pass the value as an argument to a path helper then rails should escape it automatically for you, like so:

link_to "Here", my_route_path(:foo => "bar")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top