In Rails, how to get current URL (but no paths)
If I'm in a UR开发者_开发问答L such as
http://domain.example/mysite/bla
How can I request just the URL with no paths? Such as
http://domain.example
You can use this
<%= request.protocol + request.host_with_port %>
#=> https://domain.example:3000
<%= request.protocol + request.host %>
#=> https://domain.example
Starting from Rails 3.2 you can also use
<%= request.base_url %>
#=> https://domain.example:3000
request.host
should do the trick, or:
request.port.blank? ? request.host : "#{request.host}: #{request.port}"
if you need to include the port too.
Try this
<%=request.scheme + '://' + request.host_with_port%>
If you want to see all available methods on request object then
<%=request.methods.sort%>
For protocol, domain and port
<%= "#{request.protocol + request.host}:#{request.port.to_s}" %>
Here's how you can get your current domain name.
Domain name
request.base_url
# prod: https://example.com
# dev: https://localhost:8000
Getting full path
request.original_url
# prod: https://example.com/path/
# dev: https://localhost:8000/path/
If your port could be anything other than 80 it should be included.
"#{request.protocol}#{request.host_with_port}"
I think this can be useful too, if you're not in a controller.
URI.join(url_for(only_path: false), '/').to_s
精彩评论