How do I get the current absolute URL in Ruby on Rails? - ruby-on-rails

How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.

For Rails 3.2 or Rails 4+
You should use request.original_url to get the current URL. Source code on current repo found here.
This method is documented at original_url method, but if you're curious, the implementation is:
def original_url
base_url + original_fullpath
end
For Rails 3:
You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.
For Rails 2:
You can write request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

I think that the Ruby on Rails 3.0 method is now request.fullpath.

You could use url_for(only_path: false)

DEPRECATION WARNING: Using #request_uri is deprecated. Use fullpath instead.

If you're using Rails 3.2 or Rails 4, you should use request.original_url to get the current URL.
Documentation for the method is at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url, but if you're curious, the implementation is:
def original_url
base_url + original_fullpath
end
EDIT: This is still the case for Rails 7 (Docs).

You can add this current_url method in the ApplicationController to return the current URL and allow merging in other parameters
# 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
Example Usage:
current_url --> http://...
current_url(:page=>4) --> http://...&page=4

For Ruby on Rails 3:
request.url
request.host_with_port
I fired up a debugger session and queried the request object:
request.public_methods

In Ruby on Rails 3.1.0.rc4:
request.fullpath

I needed the application URL but with the subdirectory. I used:
root_url(:only_path => false)

url_for(params)
And you can easily add some new parameter:
url_for(params.merge(:tag => "lol"))

I think request.domain would work, but what if you're in a sub directory like blah.blah.com? Something like this could work:
<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>
Change the parameters based on your path structure.
Hope that helps!

It looks like request_uri is deprecated in Ruby on Rails 3.
Using #request_uri is deprecated. Use fullpath instead.

Using Ruby 1.9.3-p194 and Ruby on Rails 3.2.6:
If request.fullpath doesn't work for you, try request.env["HTTP_REFERER"]
Here's my story below.
I got similar problem with detecting current URL (which is shown in address bar for user in her browser) for cumulative pages which combines information from different controllers, for example, http://localhost:3002/users/1/history/issues.
The user can switch to different lists of types of issues. All those lists are loaded via Ajax from different controllers/partials (without reloading).
The problem was to set the correct path for the back button in each item of the list so the back button could work correctly both in its own page and in the cumulative page history.
In case I use request.fullpath, it returns the path of last JavaScript request which is definitely not the URL I'm looking for.
So I used request.env["HTTP_REFERER"] which stores the URL of the last reloaded request.
Here's an excerpt from the partial to make a decision
- 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

This works for Ruby on Rails 3.0 and should be supported by most versions of Ruby on Rails:
request.env['REQUEST_URI']

None of the suggestions here in the thread helped me sadly, except the one where someone said he used the debugger to find what he looked for.
I've created some custom error pages instead of the standard 404 and 500, but request.url ended in /404 instead of the expected /non-existing-mumbo-jumbo.
What I needed to use was
request.original_url

If by relative, you mean just without the domain, then look into request.domain.

You can use the ruby method:
:root_url
which will get the full path with base url:
localhost:3000/bla

(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)

In Rails 3 you can use
request.original_url
http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url

you can use any one for rails 3.2:
request.original_url
or
request.env["HTTP_REFERER"]
or
request.env['REQUEST_URI']
I think it will work every where
"#{request.protocol}#{request.host}:#{request.port}#{request.fullpath}"

Rails 4.0
you can use request.original_url, output will be as given below example
get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"

You can either use
request.original_url
or
"#{request.protocol}#{request.host_with_port}"
to get the current URL.

For Rails 3.2 or Rails 4
Simply get in this way "request.original_url"
Reference: Original URL Method
For Rails 3
As request.url is deprecated.We can get absolute path by concatenating
"#{request.protocol}#{request.host_with_port}#{request.fullpath}"
For Rails 2
request.url

if you want to be specific, meaning, you know the path you need:
link_to current_path(#resource, :only_path => false), current_path(#resource)

For rails 3 :
request.fullpath

request.env["REQUEST_URI"]
works in rails 2.3.4 tested and do not know about other versions.

To get the request URL without any query parameters.
def current_url_without_parameters
request.base_url + request.path
end

You can set a variable to URI.parse(current_url), I don't see this proposal here yet and it works for me.

You can use:
request.full_path
or
request.url
Hopefully it will resolve your problem.
Cheers

To get the absolute URL which means that the from the root it can be displayed like this
<%= link_to 'Edit', edit_user_url(user) %>
The users_url helper generates a URL that includes the protocol and host
name. The users_path helper generates only the path portion.
users_url: http://localhost/users
users_path: /users

Related

Rails 5 show content based on route

I have a Rails 5 application that will have dynamic content in the header based on the current route. I realize that I can get the route and compare it with something like if(current_page?('/home')) but is this really the best way?
Think of initializing your dynamic content in controller's actions. It is the common solution for such things.
For example:
html:
<title><%= #title %></title>
controller:
def index
...
#title = 'Hello world'
...
end
Also, you can initialize dynamic content in Rails views using content_for helper method. There is a similar question about this Rails: How to change the title of a page?
If you are sure that you have to set this content in a different place and based on the current route, I advise you to use params[:controller] and params[:action] parameters, although your solution is not bad too.
I think using params[:controller], params[:action] or current_page? would be better
You can use named routes with current_page?:
if(current_page?(posts_path))
and
if(current_page?(post_path(1))
In addition, you can also check the the current path by using request
if you're in root path
request.url
#=> "http://localhost:3000"
request.path
#=> "/"

Rails current url helper

Apologies for such a simple question, but I couldn't been able to solve it myself after hours since my RoR knowledge is basically nonexistent. In the Rails application I'm working with, has been used a navigation helper to highlight active menu:
def nav_link(link_text, link_path, ico_path)
class_name = current_page?(link_path) ? 'active' : nil
content_tag :li do
link_to(link_path, class: class_name) do
image_tag("icons/#{ico_path}.svg") + content_tag(:span, link_text)
end
end
end
The circumstances have changed and current_page? is no longer a viable option, since routing now handled on the front-end. Is there a way to achieve the same functionality by retrieving, for instance, current url and check it against link_path?. I've tried a lot of things with different helpers like request.original_url, but to no avail.
request.original_url should work according to the documentation.
Returns the original request URL as a string
http://apidock.com/rails/ActionDispatch/Request/original_url
You could also try string concatenation with different variables.
request.host + request.full_path
If that doesn't work either, you could try
url_for(:only_path => false);
Use
request.url
http://api.rubyonrails.org/classes/ActionDispatch/Http/URL.html#method-i-url
or
request.path
http://www.rubydoc.info/gems/rack/Rack/Request#path-instance_method
You'll want to look at the active_link_to gem:
def nav_link(link_text, link_path, ico_path)
content_tag :li do
active_link_to link_path do
image_tag("icons/#{ico_path}.svg") + content_tag(:span, link_text)
end
end
end
Unlike the current_page? helper, active_link_to uses controller actions and model objects to determine whether you're on a specific page.
current_page? only tests against the current path, leaving you exposed if you're dealing with obscure or ajaxified routes.
--
I was going to write about how current_page? works etc, but since you mentioned that it's nonviable, I won't. I would have to question why it's nonviable though...
routing now handled on the front-end.
Surely even if you're using something like Angular with Rails, you'd have to set the routes for your app?

Get current path name in Rails

I would like to be able to get the name of the current route in a request in Ruby on Rails. I've found ways I can access the controller and action of the request, but I would like to access a string or symbol of the name.
For example, if I have a users resource;
If I go to /users/1 I would like to be able to get users_path
If I go to /users/1/edit I would like to be able to get edit_users_path
I simply want to retrieve the name of the current route on a given request.
The following code will give it to you.
Rails.application.routes.recognize_path(request.request_uri)
Note that there are a couple of exceptions that can get thrown in ActionDispatch::Routing::RouteSet (which is what is returned from Rails.application.routes) so be careful about those. You can find the implementation of the method here.
You can use the following methods to get the current url in your action but none of them will give you the name of the route like users_path
request.original_url # => www.mysite.com/users/1
request.request_uri # = > /users/1
I had to use request.original_fullpath (Rails 5.2)
You can use the current_page? method to achieve this.
current_page?(user_path(#user))
current_page?(edit_user_path(#user))
Here's a link:
current_page? method

Rails 3 change path to url

I am passing a path as a parameter, so params[:path] would be name_path(:username => #user.name (I want to pass it as a path and not a url, so putting name_url in the params isn't what I want).
Since you can only use redirect_to with a url, I need to change the path to a url before I can use redirect_to. How would I do this?
I found this method here
def path_to_url(path)
"http://#{request.host_with_port_without_standard_port_handling}/#{path.sub(%r[^/],'')}"
end
But, this was written in 2008, and I want to know if there is a better way in Rails 3?
Updated copy from original path to url post btw: also works on Rails 2
# abs or /abs -> http://myx.com/abs
# http://grosser.it/2008/11/24/rails-transform-path-to-url
def path_to_url(path)
"#{request.protocol}#{request.host_with_port.sub(/:80$/,"")}/#{path.sub(/^\//,"")}"
end
I think you can use a redirect_to with a path as long as its a route defined in the routes file for the current application. Thats seems to be the case from your question.
ie, name_path(:username => #user.name)
So the following should be valid.
redirect_to params[:path]
I ended up using
def path_to_url(path)
"http://#{request.host}/#{path.sub(%r[^/],'')}"
end

Rails 3.0.7 Restful_Authentication, Why does destroy try to log in from cookie while others do not?

I have an app that I am upgrading to Rails 3 which uses the restful_authentication plugin. I have the authenticated_system.rb in the lib directory where it seems to be able to find it. I have put puts in the library to figure out what it does on each call. When I call any method besides destroy the puts statement tells me it has logged in from session. When I try to use the destroy method in a controller (does not matter which) it tells me that it is trying to login from cookie, which fails because the system is set up not to use cookies. Why would it be doing this? The code is exactly the same for all of them and the before filter is simply:
def validate_user_type
if ( current_user.user_type == User::UserType::VIEWER )
redirect_to :controller => 'assets', :action => 'myassets'
end
This filter is applied to everything
Any ideas?
Try button_to instead of link_to for you delete actions.
I had the same problem, it was because I was using link_to with the :remote option.
This was not passing the authenticity_token in the post parameters, and therefore restful_authentication was failing.
I switched to using button_to, the authenticity_token was included and my deletes started working.
I found this, never posted though, check the application layout for csrf tags, if these are not there it will do some funky things. This was the problem.

Resources