如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对URL。
如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对URL。
当前回答
弃用警告:不支持使用#request_uri。请改用fullpath。
其他回答
你可以通过调用:
request.original_url
or
request.env['HTTP_REFERER']
在Ruby on Rails 3.1.0.rc4中:
request.fullpath
您可以在ApplicationController中添加这个current_url方法来返回当前URL,并允许合并其他参数
# https://x.com/y/1?page=1
# + current_url( :page => 3 )
# = https://x.com/y/1?page=3
def current_url(overwrite={})
url_for :only_path => false, :params => params.merge(overwrite)
end
使用示例:
current_url --> http://...
current_url(:page=>4) --> http://...&page=4
要获得绝对URL,这意味着从根目录中获取,它可以像这样显示
<%= link_to 'Edit', edit_user_url(user) %>
users_url助手生成一个包含协议和主机的URL 的名字。users_path助手只生成路径部分。
users_url: http://localhost/users
users_path: /users
在Rails 3中你可以使用
request.original_url
http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url