How to Get the Current Absolute URL in Ruby on Rails

09/26/2021

Contents

In this article, you will learn how to get the current absolute URL in Ruby on Rails.

Getting the current absolute URL

To get the current absolute URL in Ruby on Rails, you can use the request.original_url method. Here’s how you can use it in a Rails application:

In your controller action or view, use the request.original_url method to get the current absolute URL:

url = request.original_url

The url variable now contains the current absolute URL, including the protocol (http or https), domain, port (if specified), and the path. For example:

https://example.com/products/1?category=electronics

If you need to get the URL without the query string parameters, you can use the request.base_url and request.path methods instead:

url = "#{request.base_url}#{request.path}"

The url variable now contains the current absolute URL without the query string parameters. For example:

https://example.com/products/1

If you need to generate a URL for a specific route in your Rails application, you can use the url_for method:

url = url_for(controller: 'products', action: 'show', id: 1)

The url variable now contains the URL for the products#show action with the ID parameter set to 1. For example:

https://example.com/products/1