Search my site
« Convert YAML to JSON i18n internationalization locale files | Main | Crack open that MacBook Pro »

Find the current_controller? in Rails

Fine Current Creative Commons License photo credit: spacesuitcatalyst

Rails provides a very useful current_page?(link) function but I needed a way to find if I was on the current_controller?(link) for adding a css class to menu links. This was useful for when I'm on a deeplink 'users/1/edit' but want to match a menu link to 'users/'. They share the same controller but not a the whole page link.

Download the GIST

# A rails helper snippet I find helpful for building main navigation
# when you want to highlight main pages (controllers) when browser
# requests a subpage.
# eg. current request '/users/1/edit' but we want to highlight
# the menu link to '/users'. current_page? will be false but
# the current_controller? function will be true

# Find if a link is uses the current controller.
# Used in building main navigation to include
# sublinks.
def current_controller?(link)
  url_for(link).include? @controller.controller_name

# Create list elements for building navigation
def menu_link_li(text, link, classes = "", include_separator = false, new_tab = false)
    if current_controller? link
   classes += " selected"
  rescue Exception => e
    # deal with a potential error of not using the helper with a request first being made.
  if new_tab
    link_text = link_to text, link, :target => "_blank"
    link_text = link_to text, link
  html = %{
  • #{link_text}
  • } if include_separator html += %{
  • } end return html end

    PrintView Printer Friendly Version

    EmailEmail Article to Friend

    References (5)

    References allow you to track sources for this article, as well as articles that were written in response to this article.
    • Response
      This is the application of the computer field. Most of the computer expert has made the beautiful software about the finding of the current lines. This software can be presented and help us to find the current line.
    • Response
      Response: vao bong
      Find the current_controller? in Rails - Posts - zarzax the blog
    • Response
      Response: facebook
      Find the current_controller? in Rails - Posts - zarzax the blog
    • Response
      Solitaire is the game twhich need cards to play the game in the playground have the cool idea to get the chance to play online solitaire, free solitaire online, classic game solitaire and many more to play solitaire at free of cost.
    • Response

    Reader Comments

    There are no comments for this journal entry. To create a new comment, use the form below.

    PostPost a New Comment

    Enter your information below to add a new comment.

    My response is on my own website »
    Author Email (optional):
    Author URL (optional):
    All HTML will be escaped. Hyperlinks will be created for URLs automatically.