¿Cómo obtengo la URL absoluta actual en Ruby on Rails?
¿Cómo puedo obtener la URL absoluta actual en mi vista de Ruby on Rails?
El request.request_uri
solo devuelve la URL relativa.
30 answers
Para los carriles 3.2 o Carriles 4+
Debes usar request.original_url
para obtener la URL actual.
Este método está documentado en método original_url , pero si tienes curiosidad, la implementación es:
def original_url
base_url + original_fullpath
end
Para los carriles 3:
Puedes escribir "#{request.protocol}#{request.host_with_port}#{request.fullpath}"
, ya que request.url
ahora está obsoleto.
Para los carriles 2:
Puedes escribir request.url
en lugar de request.request_uri
. Esto combina el protocolo (generalmente http://) con el host, y request_uri para darle el dirección.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-12 07:32:58
Creo que el método Ruby on Rails 3.0 es ahora request.fullpath
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:52:25
Podrías usar url_for(:only_path => false)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-07 17:18:25
ADVERTENCIA DE OBSOLESCENCIA: El uso de #request_uri está obsoleto. Utilice fullpath en su lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 02:36:56
Si usted está usando Rails 3.2 o Rails 4 debería usar request.original_url
para obtener la URL actual.
La documentación para el método se encuentra en http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url pero si tienes curiosidad la implementación es:
def original_url
base_url + original_fullpath
end
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 15:24:41
Puede agregar este método current_url en ApplicationController para devolver la URL actual y permitir la fusión en otros parámetros
# 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
Ejemplo De Uso:
current_url --> http://...
current_url(:page=>4) --> http://...&page=4
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 04:19:15
Para Ruby on Rails 3:
request.url
request.host_with_port
Abrí una sesión del depurador y consulté el objeto request:
request.public_methods
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:53:42
En Ruby on Rails 3.1.0.rc4:
request.fullpath
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:53:02
Necesitaba la aplicación URL, pero con el subdirectorio. He utilizado:
root_url(:only_path => false)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:54:23
url_for(params)
Y puede agregar fácilmente algún parámetro nuevo:
url_for(params.merge(:tag => "lol"))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:54:54
Creo que la petición.el dominio funcionaría, pero ¿qué pasa si estás en un subdirectorio como blah.blah.com? Algo como esto podría funcionar:
<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>
Cambie los parámetros en función de su estructura de ruta.
Espero que ayude!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-29 22:44:55
Parece que request_uri
está obsoleto en Ruby on Rails 3.
Using #request_uri is deprecated. Use fullpath instead.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:52:44
Esto funciona para Ruby on Rails 3.0 y debería ser soportado por la mayoría de las versiones de Ruby on Rails:
request.env['REQUEST_URI']
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:55:38
Usando Ruby 1.9.3-p194 y Ruby on Rails 3.2.6:
Si lo solicita.fullpath no funciona para usted, intente solicitud.env ["HTTP_REFERER"]
Aquí está mi historia a continuación.
Tengo un problema similar con la detección de URL actual (que se muestra en la barra de direcciones para el usuario en su navegador) para las páginas acumulativas que combina información de diferentes controladores, por ejemplo, http://localhost:3002/users/1/history/issues
.
El usuario puede cambiar a diferentes listas de tipos de problemas. Todas esas listas son cargado a través de Ajax desde diferentes controladores / parciales (sin recargar).
El problema era establecer la ruta correcta para el botón atrás en cada elemento de la lista para que el botón atrás pudiera funcionar correctamente tanto en su propia página como en el historial de la página acumulada .
En caso de que use solicitud.fullpath , devuelve la ruta de la última solicitud de JavaScript que definitivamente no es la URL que estoy buscando.
Así que usé solicitud.env ["HTTP_REFERER"] que almacena la URL de la última solicitud recargada.
Aquí hay un extracto del parcial para tomar una decisión
- if request.env["HTTP_REFERER"].to_s.scan("history").length > 0
- back_url = user_history_issue_path(@user, list: "needed_type")
- else
- back_url = user_needed_type_issue_path(@user)
- remote ||= false
=link_to t("static.back"), back_url, :remote => remote
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:58:32
Ninguna de las sugerencias aquí en el hilo me ayudó tristemente, excepto la que alguien dijo que usó el depurador para encontrar lo que buscaba.
He creado algunas páginas de error personalizadas en lugar del estándar 404 y 500, pero request.url
terminó en /404
en lugar del esperado /non-existing-mumbo-jumbo
.
Lo que necesitaba usar era
request.original_url
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-04 12:58:09
Si por relativo, quieres decir solo sin el dominio, entonces mira en request.domain
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-07 15:51:21
Puedes usar el método ruby:
:root_url
Que obtendrá la ruta completa con la url base:
localhost:3000/bla
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 09:07:14
(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-11 07:21:17
En Rails 3 puedes usar
request.original_url
Http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-13 11:58:41
Rails 4.0
Puede usar request.original_url
, la salida será como se muestra a continuación ejemplo
get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-26 14:07:19
Si quieres ser específico, es decir, sabes el camino que necesitas:
link_to current_path(@resource, :only_path => false), current_path(@resource)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-01 22:30:40
Para los carriles 3:
Solicitud.fullpath
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-10 08:43:32
Puede usar cualquiera para rails 3.2:
request.original_url
or
request.env["HTTP_REFERER"]
or
request.env['REQUEST_URI']
Creo que funcionará en todas partes
"#{request.protocol}#{request.host}:#{request.port}#{request.fullpath}"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-11 05:17:06
request.env["REQUEST_URI"]
Funciona en rails 2.3.4 probado y no conoce otras versiones.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-02 21:15:22
Para obtener la URL de la solicitud sin ningún parámetro de consulta.
def current_url_without_parameters
request.base_url + request.path
end
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 13:34:29
Puede usar
request.original_url
O
"#{request.protocol}#{request.host_with_port}"
Para obtener la URL actual.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-02 07:07:32
Para los carriles 3.2 o Carriles 4 Simplemente obtener de esta manera " solicitud.original_url" Referencia: URL Original Method
Para los carriles 3 Como petición.la url está obsoleta.Podemos obtener el camino absoluto concatenando
"#{request.protocol}#{request.host_with_port}#{request.fullpath}"
Para los carriles 2
request.url
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-12 08:43:58
Puedes usar:
request.full_path
O
request.url
Esperemos que resuelva su problema.
Salud
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-18 05:41:38
Puede establecer una variable en URI.parse(current_url)
, no veo esta propuesta aquí todavía y funciona para mí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-04 20:27:50
Para obtener la URL absoluta, lo que significa que el from the root
se puede mostrar así
<%= link_to 'Edit', edit_user_url(user) %>
El helper users_url genera una URL que incluye el protocolo y el host nombre. El helper users_path genera solo la porción de ruta.
users_url: http://localhost/users
users_path: /users
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-12 14:41:42