【问题标题】:Rails 4 routes namespace / concern with url variables or parametersRails 4 路由命名空间/关注 url 变量或参数
【发布时间】:2013-11-28 10:24:06
【问题描述】:

我有一个应用程序的日历部分有一些烦人的特定路线。它们看起来像这样:

MyApp::Application.routes.draw do
  ...
  day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
  get 'days/:month/:day/:year', to: 'schedule#day', constraints: day_constraints, as: :schedule_day
  get 'days/:month/:day/:year/print', to: 'schedule#day_print', constraints: day_constraints
  get 'days/:month/:day/:year/route', to: 'routes#index', constraints: day_constraints
  ...
end

如您所见,这里有很多重复。它们都路由到调度控制器。我想知道是否有办法减少重复。我在想一个名称空间或一个看起来像这样的问题:

MyApp::Application.routes.draw do
  ...
  day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
  namespace 'days/:month/:day/:year' constraints: day_contstraints do
    get 'print', to: 'schedule#day_print'
    get 'route', to: 'routes#index'

    root to: 'schedule#day'
  end
  ...
end

但这会引发错误:

'day/:month/:day/:year/schedule' is not a supported controller name. This can lead to potential routing problems.

关于如何清理它的任何建议?

【问题讨论】:

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


    【解决方案1】:

    尝试使用scope 代替namespaceget "/" => "schedule#day" 代替root to: 'schedule#day'

    day_constraints = { year: /\d{4}/, month: /\d{1,2}/, day: /\d{1,2}/ }
    scope 'days/:month/:day/:year', constraints: day_constraints do
      get 'print', to: 'schedule#day_print'
      get 'route', to: 'routes#index'
      get '/', to: 'schedule#day'
    end
    

    我还必须在范围和约束之间添加一个逗号。

    【讨论】:

    • 感谢您的建议,但这并不完全正确。您也可以在命名空间上使用root。事实上,同一个应用程序就是这样做的。它只是根植于命名空间的基础。因此,如果您有一个namespace :schedule 并给它一个root to: 'schedule#index',那么schedule_root_path 会将您发送到/schedule。 @jvperrin
    • @johnnyPando 我已经更新了我的答案并在一个真实的应用程序中对其进行了测试,所以它现在应该可以正常工作了。
    • 太棒了!做到了。非常感谢。
    猜你喜欢
    • 2015-07-02
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多