Rails current url helper

14,106

Solution 1

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);

Solution 2

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

Solution 3

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?

Share:
14,106
curious_gudleif
Author by

curious_gudleif

Updated on June 25, 2022

Comments

  • curious_gudleif
    curious_gudleif almost 2 years

    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.