代码之家  ›  专栏  ›  技术社区  ›  Ilja KO

如何用动态参数约束作用域路由,使其仅具有特定的参数组合

  •  0
  • Ilja KO  · 技术社区  · 6 年前

    我正在为一个论坛制作一个Rails应用程序,并拥有:

    路线.rb

    @@category_filters=/general|off-topic|ruby-on-rails/
    @@subcategory_filters = /announcements|news|member-introductions|suggestions|
                         developers|tutorials|jobs-and-projects|miscellaneous|
                         funny-stuff/
    
    Rails.application.routes.draw do
      scope '(:locale)', locale: /en|de/ do
        ...
        scope '/:category/:subcategory', category: @@category_filters,
                                         subcategory: @@subcategory_filters do
          resources :posts
        end
      end
      ...
    end
    

    我要我的路线 posts 在URL中有两个参数调用 category subcategory

    我的应用程序中有这个结构(这是一个论坛)

    • 一般的
      • 公告
      • 建议
      • 会员介绍
    • 铁轨上的红宝石
      • 新闻
      • 开发者
      • 教程
    • 离题
      • 其他
      • 工作和项目
      • 有趣的东西

    现在这个可以用了 routes.rb 我在上面介绍过,但是我想进一步限制路由,以便帖子在URL中只有特定的参数组合。

    例如,这应该是正常的:

    .../general/announcements/posts/...
    

    但不是这样:

    .../general/tutorials/posts...
    

    因为根据我的网站设计 tutorials 不是的子类别 general 但是 ruby-on-rails

    有人知道如何改变 路线.rb 文件以便它像我希望的那样工作?

    2 回复  |  直到 6 年前
        1
  •  0
  •   coreyward    6 年前

    这里不使用正则表达式,只应使用 custom route constraint :

    class Category
      OPTIONS = {
        "general" => [
          "announcements",
          "suggestions",
          "member-introductions",
        ],
        "ruby-on-rails" => [
          "news",
          "developers",
          "tutorials",
        ],
        "off-topic" => [
          "miscellaneous",
          "jobs-and-projects",
          "funny-stuff",
        ]
      }
    end
    
    class CategoryConstraint 
      def matches?(request)
        options = Category::OPTIONS
        category = request.params[:category]
        subcategory = request.params[:subcategory]
    
        options[category] && options[category].include?(subcategory)  
      end
    end
    
    Rails.application.routes.draw do
      resources :posts, constraints: CategoryConstraint.new
    end
    

    您可以使用将其简化为DSL only .

        2
  •  -1
  •   Ilja KO    6 年前

    我用一张外卡做到了这一点:

    Rails.application.routes.draw do
      @category_filters    = /(?x)general\/suggestions|
                                  general\/member-introduction|
                                  general\/announcements|
                                  off-topic\/jobs-and-projects|
                                  off-topic\/miscellaneous|
                                  off-topic\/funny-stuff|
                                  ruby-on-rails\/news|
                                  ruby-on-rails\/developers|
                                  ruby-on-rails\/tutorials/
      scope '(:locale)', locale: /en|de/ do
       ...
        scope '*category', category: @category_filters do
          resources :posts, only: %i[new edit index show]
        end
        ...
    end