43

request.url returns me this : http://localhost:3000/page?foo=bar.

Is there a method I can call to get http://localhost:3000/page , or do I have to parse the string to strip get parameters?

MrRuru
  • 1,932
  • 2
  • 20
  • 24

3 Answers3

58

request.path should return what you're looking for if you're not concerned about the hostname. Otherwise you might try:

url_for(:only_path => false, :overwrite_params=>nil)
Community
  • 1
  • 1
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    I also ran into the recursive parameters problem, `/controller/action?param=1?param=2?param=3`, but the request.path worked excellent for me. – Justus Romijn Apr 12 '11 at 08:54
  • 1
    The problem with the above method is that if there are multiple paths for the same type of resource (say for a publication where some things are labeled "/news/post-name" and others "/blog-name/post-name"), then you could get the wrong path back. – thekingoftruth Jul 16 '14 at 17:30
  • @thekingoftruth That's true, but the highest priority route will be used, so be sure to order them correctly. – tadman Jul 16 '14 at 18:31
  • @tadman Good point. However, sometimes there is no priority between two routes--one model can be accessed from various urls depending on how they're tagged. (e.g. Movies section, TV section, Comedy section, etc.) In this case, url_for is not a viable solution. I will post the solution I found as a separate answer. – thekingoftruth Jul 16 '14 at 21:18
  • 1
    It's possible to parse the current URL with the `URI` module, rip off the queries, and re-emit that as an alternative. – tadman Jul 16 '14 at 22:07
18

To get the request URL without any query parameters.

def current_url_without_parameters
  request.base_url + request.path
end
Nerve
  • 6,463
  • 4
  • 29
  • 29
12

I use the following:

request.original_url.split('?').first

It does not regenerate the path, and therefore gives you exactly the url that the end-user sees in their browser, minus query parameters.

thekingoftruth
  • 1,711
  • 1
  • 25
  • 24