Route Globbing In Ruby on Rails
- Last modified atRoute globbing is a way to specify parameter from request should be matched to all remaining parts of a route. For example in Rails 4:
get 'users/*xyz' => 'users#list'
When client send GET request with URL /users/foo/bar
, Rails will automatically match to action list in controller users with params[:xyz]
equals foo/bar
. The fragments prefixed with a star are called “wildcard segments”.
Wildcard segments can contain request format. For example, By requesting /users/foo/bar.json
, params[:xyz]
will equals foo/bar
with request format of JSON. If you want to make the format segment must be exist, in config/routes.rb you can supply format: true
like this:
get 'users/*xyz' => 'users#list', format: true
A route have more than one wildcard segments. Wildcard segments can be anywhere and can combine with other parameters. For example:
get '*abc/users/*xyz/:username' => 'users#list'
So, if client make GET request to /yuhuu/woohoo/users/foo/bar/example
as the result params[:abc]
equals yuhuu/wohoo
, params[:xyz]
equals foo/bar
, and params[:username]
equals example
.
- Tags:
- #ruby on rails
- #route
- #rails
- #ruby
Sponsored Links
- Register to Digital Ocean cloud with this link and get $200 credit
- Looking for cheap CDN? Bunny is the answer
- Alternative Cloud besides AWS and Digital Ocean