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
P.S. 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, e.g.:
my_path = URI(request.referer).path
# => /books
Rails.application.routes.recognize_path(my_path)
# => {:action=>"show", :controller=>"books", :page=>"4"}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With