Rails:如何获得控制器; Restful命名路由的方法名称?

时间:2014-06-23 12:37:28

标签: ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1

在我的HTML视图

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

在check_link帮助方法中:

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

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

  end

但是,我在浏览器中收到如下错误:

  

未定义的方法`controller&#39; for&#34; / admin / dashboard&#34;:String

现在,我的问题是如何从&#34;命名路径(dashboard_path)&#34;中找到控制器和方法名称。请有人帮我解决这个问题。

5 个答案:

答案 0 :(得分:4)

您可以使用Rails.application.routes.recognize_path来提取:controller: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

示例

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"}

如果您的路径不正确,那么您将得到以下内容:

Rails.application.routes.recognize_path('dashboards/index')

# output will be
=> {:controller=>"pages", :action=>"page_not_found", :url=>"dashboards/index"}

希望你觉得这很有用。

答案 1 :(得分:0)

ActionDispatch :: Routing :: RouteSet #recognition_path

这可能会有所帮助。这将给出路径映射的控制器操作。

答案 2 :(得分:0)

Rails.application.routes.recognize_path('/my_path')

答案 3 :(得分:-1)

dashboard_path是一个字符串,因此您无法在其上调用#controller和#action方法。尝试只是controller_name和method_name。或者params [:controller]和params [:action]

答案 4 :(得分:-1)

params哈希将始终包含:controller:action个键,您可以尝试这个

def check_link(path)
    controller_name = params[:controller]
    method_name = params[:action]
end