1

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

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.

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

4

1 回答 1

2

尝试使用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

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

于 2013-11-15T05:22:38.717 回答