简体   繁体   中英

Rails URI(request.referer).path regexp

I would like to know from cart controller from which URL I come: If I come from '/' or '/search' the parameter is a Serie Model, if I come from /'1-9+' it's a Season Model and finally /'1-9+/1-9+' is a Chapter Model.

I've seen that URI(request.referer).path shows the path, but I don't know how to make that regexp.

There is any simple way of knowing from what view it comes? I have problems storing them because they are different Models, and the parameter is the primary_key so I don't know on which model I have to search that key.

A better way to differentiate these requests would be to not use regexp but to declare appropriate routes in your routes.rb file

get '/' => 'series#index'

get '/search' => 'series#search'

get '/:season' => 'seasons#show'

get '/:season/:chapter' => 'chapters#show'

In the last route, params[:season] and params[:chapter] will be set based on your URL

If from within the controller action you want to know which route the request came from, better to let rails routing handle the regex part for you and you can simply add identifiers as extra parameter from the routes.rb itself.

get '/' => 'your_controller#your_action', :type => "Series"
get '/search' => 'your_controller#your_action', :type => "Series"
get '/:season' => 'your_controller#your_action', :type => "Season"
get '/:season/:chapter' => 'your_controller#your_action', :type => "Chapter"

the identifier will be available in your controller action as params[:type] in this case

Also as a good practice, never begin your routes with variables. Always namespace them. Otherwise they will start getting matched with any other routes. for eg use get 'some_namespace/:season' instead of get '/:season'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM