我有一个应用程序,它为应用程序的日历部分提供了一些烦人的特定路径。它们看起来像这样:
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.
有关如何清理它的任何建议吗?
答案 0 :(得分:2)
尝试使用scope
代替namespace
和get "/" => "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
我还必须在范围和约束之间添加逗号。