【问题标题】:Is there a rails way to get current route's scope?有没有一种获取当前路线范围的方法?
【发布时间】:2012-10-22 18:40:27
【问题描述】:

如果您的 routes.rb 文件中有一个范围,例如:

scope "/account" do
  resources :items
end

如何确定当前页面是否在“帐户”部分?是否意味着将在“帐户”部分考虑以下项目?

/account/items
/account/item/1
/account/item/1/edit

我知道这可以通过对请求变量执行字符串比较来实现,但我很好奇是否有确定此信息的“rails 方式”。

感谢您的任何意见。

【问题讨论】:

    标签: ruby-on-rails url-routing


    【解决方案1】:

    我刚才也遇到了同样的问题。我所做的就是在作用域中添加一个参数:

    scope '/me', me_scope: true do
      # ...
    end
    

    这样我可以在控制器中查找它:

    class ApplicationController < ActionController::Base
      def me_scope?
        params[:me_scope].eql? true
      end
    end
    

    不是最干净的解决方案,但它有效..

    【讨论】:

    • 小心,因为这可能会在您的测试中抛出各种ActionController::UrlGenerationErrors。
    • 我也在寻找(并期待)一个成熟的解决方案,但这似乎很容易工作。
    • @cseelus:有趣!比如什么?
    猜你喜欢
    • 2011-01-07
    • 2010-10-10
    • 2011-12-29
    • 2020-03-27
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多