As we know from this post , in Rails, you can get the previous url by calling
request.referrer
But how do you check if the previous url matches one of the restful paths in your Rails application?
By restful paths, I mean paths provided by Rails, such as,
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.
One particular case, in my application, is that request.referrer can be "localhost:3000/books?page=4"
and I want to it to match
books_path
which returns "/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. I just thought there might be a better way in Rails.
You could extract the path portion of the request.referer
using the following:
URI(request.referer).path
You can then use Rails.application.routes.recognize_path
to check if path maps to a controller and action, eg:
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. 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]. This would still work properly.
Since recognize_path
was deprecated, this is another way of doing it:
Name your route in your routes config using the as
keyword:
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
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.