¿Cómo obtener el controlador actual para una URL en Rails?

I'm using this code to highlight currently active menu tab with Twitter Bootstrap:

  def nav_link_to(link_text, link_path, options = nil)
    class_name = current_page?(link_path) ? 'active' : ''

    content_tag(:li, :class => class_name) do
      link_to link_text, link_path, options

This of course makes the link active, only if the given link IS the current page. How can I change this function, such that it would return 'active' for any links below current controller? In other words, for all actions for Posts controller, the links would be active?

preguntado el 30 de junio de 12 a las 16:06

4 Respuestas

Puedes usar controller_name to get the name of the current controller.

Respondido el 26 de junio de 15 a las 03:06

Yes, but the question was - how do I check that a link or URL belongs to some controller - this is what the code is about. - Halcón

You don't. But you can just use it manually: link_to 'posts', posts_path, :class => params[:controller] == 'posts' ? 'active' : '' - rfunduk

You could, like, regex it... :class => path =~ params[:controller] ? 'active' : ''... but that's seems gross to me. - rfunduk

Guides recommend to use controller_name en lugar de params[:controller]. - jdoe

using controller_name and/or action_name are the usual way to solve this problem - sist.

This could be solved with:


respondido 15 nov., 12:12

params[:controller] returns controller name with its namespace.

If you want to get controller name only you should use controller.controller_name.

class Admin::Posts; end

# from the view
=> 'admin/posts'

=> 'posts'

Respondido el 11 de junio de 14 a las 10:06

Not sure if I read this correctly, but you shouldn't use a get param to see the current controller.

¿Has probado usar request.path ? In other words, check if any of the links below include 'request.path' in their path...

Respondido el 24 de junio de 13 a las 18:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.