Every Rails controller includes two accessor methods pointing to the request and the response objects associated with the current HTTP request cycle. The request
method returns an instance of the ActionDispatch::Request
class, which wraps the HTTP request and provides a nice API to inspect the request.
Use original_url
method on the request
object to get the current absolute URL.
# Returns the original request URL as a `String`
# get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"
Here's the source code for this method.
def original_url
base_url + original_fullpath
end
The base_url
returns the URL containing the protocol and the domain, and the original_fullpath
returns a String with the requested path, including the query params.
If you don't care about the protocol and domain, use the original_fullpath
or the fullpath
method on the request. It returns the path including params.
# get "/articles"
request.fullpath # => "/articles"
# get "/articles?page=2"
request.fullpath # => "/articles?page=2"
Here's some other information available on the request object.
Property of request | Purpose |
---|---|
host | The hostname used for this request. |
domain(n=2) | The hostname's first n segments, starting from the right (the TLD). |
format | The content type requested by the client. |
method | The HTTP method used for the request. |
get? , post? , patch? , put? , delete? , head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
headers | Returns a hash containing the headers associated with the request. |
port | The port number (integer) used for the request. |
protocol | Returns a string containing the protocol used plus "://", for example "http://". |
query_string | The query string part of the URL, i.e., everything after "?". |
remote_ip | The IP address of the client. |
url | The entire URL used for the request. |