【问题标题】:Rails: Catch a request in a scope when the request doesn't match anything in the scopeRails:当请求与范围内的任何内容都不匹配时,在范围内捕获请求
【发布时间】:2018-05-21 15:16:38
【问题描述】:

让我们使用以下路由器:

Rails.application.routes.draw do
  scope ":locale", locale: /en|nl/ do
    get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
  end

  root to: "pages#simple_action"
  get "/:slug", to: "pages#simple_action", constraints: { slug: /.*/ }
end

如果请求指定了语言环境,则作用域会捕获它并将其转发给pages#prefixed_action。如果不是,请求被转发到pages#simple_action

我的问题是,如果我在浏览器中输入localhost:3000/en,它不会被范围捕获。我该如何安排呢?

Edit1:我希望将请求路由到“pages#prefixed_action”

Edit2:在代码示例中添加了root 声明

【问题讨论】:

  • 除了下面@maicher 的精彩回答,我认为constraints: { slug: /.*/ } 子句是不必要的。

标签: ruby-on-rails ruby ruby-on-rails-4 routes


【解决方案1】:

其中一种可能性是在范围内指定root

scope ":locale", locale: /en|nl/ do
  root 'pages#prefixed_action'
  get "/:slug", to: "pages#prefixed_action", constraints: { slug: /.*/ }
end

【讨论】:

  • 抱歉,我的问题不够准确。范围之外已经有一个root 声明。因此在作用域内添加/admin/cms/block_contents/42537/edit 会产生错误ArgumentError at / Invalid route name, already in use: 'root'
  • 那么你可以直接使用get '/' => ...,你不需要 "root" 方法。
  • 根指作用域。因此,您已经在范围之外拥有一个根并不重要。发生错误,因为两者(根和进入范围内)都指向相同的控制器操作pages#prefixed_action。为 root 指定另一个操作。例如:root 'pages#index'(也在PagesController 内创建方法index)。
  • 谢谢,但添加另一个动作不是我想要的。我希望将/en 请求发送到“pages#prefixed_action”。
【解决方案2】:

也许就是这样:

get '/:locale', to: "pages#prefixed_action", constraints: { locale: /(en|nl)/ }
get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ }    

如果您的目标是发送到 pages#prefixed_action,路径为 /en/nl 以及所有其他到 pages#simple_action。如果是的话,把

get '/:locale', to: "pages#simple_action", constraints: { locale: /.*/ } 

作为您路线中的最后一条路线

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多