【问题标题】:Rails 3: Get current view's path helper?Rails 3:获取当前视图的路径助手?
【发布时间】:2011-09-22 01:27:14
【问题描述】:

我有兴趣为我的布局创建一个标准,其中每个视图都将包装在一个根据特定约定命名的容器中。

例如,如果我有:

resources :foos

我希望视图像这样包裹在 div 中:

<div id="foos_view"> foos#index here </div>
<div id="foo_view"> foos#show here </div>
<div id="new_foo_view"> foos#new here </div>
<div id="edit_foo_view"> foos#edit here </div>

所以,基本上我想使用路线名称,但用“路径”代替“视图”。

我的问题是,有没有办法获取当前视图的路线名称?

即。如果我的请求是example.com/foos/new,我可以在视图或控制器中调用什么来返回new_foo_path

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 path views routes


    【解决方案1】:

    我想不出一个简单的方法来做到这一点,因为路径助手只需调用path_for() 并填写所需的参数,因此没有方法调用可以反向执行。

    但是,这是 Ruby,因此编写一个快速帮助程序来返回您想要的字符串是相当容易的。当前控制器名称可以通过controller.controller_name访问,动作名称可以通过controller.action_name访问。

    你应该这样做:

    def html_id
    
       string = ""
    
       if controller.action_name =~ /new|edit/
          string += controller.action_name + "_"
       end
    
       if controller.action_name =~ /index|create/
         string += controller.controller_name
       else
         string += controller.controller_name.singularize
       end
    
       return string += "_view"
    
     end
    

    【讨论】:

    • 宾果游戏。我不知道controller.controller_name 方法,谢谢:)
    最近更新 更多