ruby-on-rails-3 - 导轨 : How to get the controller & method name of Restfull named routes?

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

在我的 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/

相关文章:

ruby-on-rails - ruby 应用程序中的安全性 : Role defined can be misused via url edit and changes.

ruby-on-rails-3 - 样式占位符与 best_in_place 的值不同

ruby-on-rails - Ruby on Rails : dependent object destroyed when transfered from guest user to registered user

ruby-on-rails - 如何使用 Twitter Bootstrap 图标而不是链接?

mysql - 如何从 Rails 中的连接模型添加字段的总和?

ruby-on-rails - 在 [] (Gem::LoadError) 中找不到 rails (>= 0)

ruby-on-rails - Capistrano 部署和 schema.rb

ruby-on-rails - 对 Rails 4 API 的 POST 请求的空参数

ruby-on-rails - 正确的 Semantic-UI/Bower/Rails 4 配置

ruby-on-rails - 如何更改 Rails 脚手架中的默认模型模板?