在我的 HTML View 中
<% 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
但是,我在浏览器中收到如下错误:
undefined method `controller' for "/admin/dashboard":String
现在,我的问题是如何从“命名路由(dashboard_path)”中找到 Controller 和方法名称。请有人帮我解决这个问题。
最佳答案
您可以使用 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"}
希望您觉得这很有用。
关于ruby-on-rails-3 - 导轨 : How to get the controller & method name of Restfull named routes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24366140/