简体   繁体   English

Rails URI(request.referer).path regexp

[英]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.我想从购物车控制器知道我来自哪个 URL:如果我来自 '/' 或 '/search' 参数是 Serie 模型,如果我来自 /'1-9+' 它是一个季节模型,最后/'1-9+/1-9+' 是章节模型。

I've seen that URI(request.referer).path shows the path, but I don't know how to make that regexp.我已经看到URI(request.referer).path显示了路径,但我不知道如何制作正则表达式。

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.我在存储它们时遇到问题,因为它们是不同的模型,并且参数是 primary_key 所以我不知道我必须在哪个模型上搜索该键。

A better way to differentiate these requests would be to not use regexp but to declare appropriate routes in your routes.rb file区分这些请求的更好方法是不使用正则表达式,而是在 routes.rb 文件中声明适当的路由

get '/' => 'series#index' get '/' => 'series#index'

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

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

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

In the last route, params[:season] and params[:chapter] will be set based on your URL在最后一条路线中, params[:season] 和 params[:chapter] 将根据您的 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.如果在控制器操作中您想知道请求来自哪个路由,最好让 rails 路由为您处理正则表达式部分,您可以简单地从 routes.rb 本身添加标识符作为额外参数。

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在这种情况下,标识符将作为 params[:type] 在您的控制器操作中可用

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'例如,使用get 'some_namespace/:season'而不是get '/:season'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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