Search code examples
ruby-on-rails-3ruby-on-rails-4ruby-on-rails-3.2ruby-on-rails-3.1

Rails: How to get the controller & method name of Restfull named routes?


In my HTML View

<% if check_link(dashboard_path) %>
  <%= link_to "Products", dashboard_path, class: controller_name == "dashboard" ? "active" : nil %>
<% end %>

In check_link helper method:

  def check_link(path)
    controller_name = path.controller
    method_name = path.action

    then i have some extra access verification code ............

  end

But, I am getting error like below in the browser:

undefined method `controller' for "/admin/dashboard":String

Now, My question is how to find the controller and method name from the "Named routes(dashboard_path)". Please someone help me to resolve this issue.


Solution

  • You can use Rails.application.routes.recognize_path for extracting your :controller and :action

    def check_link(path)
      extracted_path =  Rails.application.routes.recognize_path(path)
    
    
      controller = extracted_path[:controller]
      action = extracted_path[:action]
    
      # your rest of the codes goes here
    end
    

    Example

    Rails.application.routes.recognize_path('/parties/autocomplete_party_name_last', {:method => :get})
    
    # Output will be    
    {:action=>"autocomplete_party_name_last", :controller=>"parties"}
    
    OR 
    
    Rails.application.routes.recognize_path('/transcriptions/2/edit')
    
    # Output will be    
    => {:action=>"edit", :controller=>"transcriptions", :id=>"2"}
    

    If your path is incorrect then you will get something like this:

    Rails.application.routes.recognize_path('dashboards/index')
    
    # output will be
    => {:controller=>"pages", :action=>"page_not_found", :url=>"dashboards/index"}
    

    Hope you find this useful.