Routes with multiple, optional, and pretty parameters

一个人想着一个人 提交于 2019-12-08 01:22:31

问题


I have a situation where I'm in need to constructing pretty url paths.

I have a FilesController that need to handle URLs like:

mydomain.com/files/path/dir1/dir2/user/bob
mydomain.com/files/path/dir1/user/bob
mydomain.com/files/path/dir1
mydomain.com/files/user/bob

In the controller, I want params[:path] to contain everything between /path and /user and params[:user] to contain anything after /user (assuming only one user and it's optional).

I'm looking for the best way to do this, preferable with just one statement in the routes.rb file. The trickiest part, I think, is that after /path an actual path to a file might be provided, N times deep.


回答1:


You want route globbing:

match 'files/*path/user/:user' => 'user#files'

You might also need to add an additional route for the case where there is no path:

match 'files/user/:user' => 'user#files'



回答2:


Thanks to Chris Heald's answer, I ended up going with this, which fit the scenario:

match 'files/user/:user' => 'files#index'
match 'files/path/*path/user/:user' => 'files#index'
match 'files/path/*path' => 'files#index'

Still wondering if this could've been handled with a one-liner.



来源:https://stackoverflow.com/questions/14007593/routes-with-multiple-optional-and-pretty-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!