使用link_to:
<%= link_to('View', group_url(136, :only_path => false)) %>
您可以使用only_path获取url输出http://www.site.com/groups/1
如果没有only_path,则得到/groups/1
如何在rails中得到路径?在link_to之外?如何获取:http://www.site.com
原因是我想创建哈希深度链接的url,所以我正在考虑做:
<%= link_to('View', XXXXXX + "#" +group_url(136, :only_path => true)) %>
其中XXXXXX为url, http://www.site.com
它会给我我想要的:
http://www.site.com/#/groups/1
谢谢
request.host
返回host ("www.your_site.com")
request.protocol
返回协议,例如http://
或https//
request.host_with_port
返回端口与主机("www.your_site.com:3456")
<%= link_to('View', request.host + "#" +group_url(136, :only_path => true)) %>
<%= link_to('View', request.protocol + request.host + "#" +group_url(136, :only_path => true)) %>
<%= link_to('View', request.protocol + request.host_with_port + "#" +group_url(136, :only_path => true)) %>
编辑
黑客:
host = group_url(136).gsub(/#{group_url(136, :only_path => true)}/, "")
或
url = group_url(136)
path = group_path(136)
host = url.gsub(/#{path}/, "")
在控制器中,request.env['HTTP_HOST']
将包含传入请求的主机部分,因此您可以创建一个helper方法来返回一个格式正确的"base url",执行如下操作:
def site_root_url
if request.env['HTTPS'] == 'on'
proto = 'https'
else
proto = 'http'
end
"#{proto}://#{request.env['HTTP_HOST']}"
end