简体   繁体   English

你如何确定request.referrer是否匹配Rails的restful路径?

[英]how do you determine if request.referrer matches a Rails restful path?

As we know from this post , in Rails, you can get the previous url by calling 正如我们从这篇文章中所知,在Rails中,您可以通过调用获取前一个URL

request.referrer

But how do you check if the previous url matches one of the restful paths in your Rails application? 但是,如何检查前一个URL是否与Rails应用程序中的其余路径匹配?

By restful paths, I mean paths provided by Rails, such as, 通过宁静的路径,我指的是Rails提供的路径,例如,

books_path
book_path(book)
edit_book_path(book)

Of course I can do a regular expression string match on request.referrer, but I think it's a bit ugly. 当然我可以在request.referrer上做一个正则表达式字符串匹配,但我觉得它有点难看。

One particular case, in my application, is that request.referrer can be "localhost:3000/books?page=4" 在我的应用程序中,一个特殊情况是request.referrer可以是“localhost:3000 / books?page = 4”

and I want to it to match 我想要它匹配

books_path

which returns "/books" 返回“/ books”

In this case, how can I check if there's a match without doing regular expression string match? 在这种情况下,如何在不进行正则表达式字符串匹配的情况下检查是否存在匹配? (if this is at all possible) (如果这是可能的话)

Thanks 谢谢

PS I have tried regular expression string match, and it works. PS我试过正则表达式字符串匹配,它的工作原理。 I just thought there might be a better way in Rails. 我只是觉得在Rails中可能有更好的方法。

You could extract the path portion of the request.referer using the following: 您可以使用以下方法提取request.referer的路径部分:

URI(request.referer).path

You can then use Rails.application.routes.recognize_path to check if path maps to a controller and action, eg: 然后,您可以使用Rails.application.routes.recognize_path检查路径是否映射到控制器和操作,例如:

my_path = URI(request.referer).path 
# => /books

Rails.application.routes.recognize_path(my_path)
# => {:action=>"show", :controller=>"books", :page=>"4"}

Though not certain of what you want to do with that, pretty sure rails support better ways of controlling redirects. 虽然不确定你想要做什么,但相当确定rails支持更好的控制重定向的方法。 Nevertheless, I guess this is what you are looking for: 不过,我想这就是你要找的东西:

request.referer == books_url(page: params[:page])

UPDATED: 更新:

This way, even if there's no params[:page]. 这样,即使没有参数[:page]。 This would still work properly. 这仍然可以正常工作。

Since recognize_path was deprecated, this is another way of doing it: 由于recognize_path被废弃,这是做的另一种方式:

Name your route in your routes config using the as keyword: 使用as关键字在路由配置中命名您的路由:

get 'foo/bar' => 'foo#bar', as: :foo_bar

Then you can do the check like this: 然后你可以像这样检查:

if URI(request.referer).path == foo_bar_path
  do_something()
end

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

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