In Rails, how to get current url (but no paths)

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


If I'm in a URL such as

http://domain.com/mysite/bla

How can I request just the URL with no paths? Such as

http://domain.com 

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can use this

<%= request.protocol + request.host_with_port %>
#=> https://domain.com:3000
<%= request.protocol + request.host %>
#=> https://domain.com

Starting from Rails 3.2 you can also use

<%= request.base_url %>
#=> https://domain.com:3000

Solution 2 - Ruby on-Rails

request.host should do the trick, or:

request.port.blank? ? request.host : "#{request.host}: #{request.port}"

if you need to include the port too.

Solution 3 - Ruby on-Rails

Try this

<%=request.scheme + '://' + request.host_with_port%>

If you want to see all available methods on request object then

<%=request.methods.sort%>

Solution 4 - Ruby on-Rails

For protocol, domain and port

<%= "#{request.protocol + request.host}:#{request.port.to_s}" %>

Solution 5 - Ruby on-Rails

If your port could be anything other than 80 it should be included.

"#{request.protocol}#{request.host_with_port}"

Solution 6 - Ruby on-Rails

I think this can be useful too, if you're not in a controller.

URI.join(url_for(only_path: false), '/').to_s 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - Ruby on-Railsfl00rView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPravinView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAshishView Answer on Stackoverflow
Solution 4 - Ruby on-RailsKulbir SainiView Answer on Stackoverflow
Solution 5 - Ruby on-RailsRohanthewizView Answer on Stackoverflow
Solution 6 - Ruby on-RailskangkyuView Answer on Stackoverflow