2013-11-15 81 views
1

我有一個應用程序,有一些令人討厭的特定路線的應用程序的日曆部分。他們看起來像這樣:Rails 4路由命名空間/關注URL變量或參數

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. 

如何清理它的任何建議?

回答

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 

我也不得不添加的範圍和約束之間的逗號。

+0

感謝您的建議,但這不完全正確。你也可以在命名空間使用'root'。事實上,該應用程序也是如此。它只是源於名稱空間的基礎。所以如果你有一個'namespace:schedule',並且給它一個'root':'schedule#index''那麼'schedule_root_path'會將你發送到'/ schedule'。 @jvperrin – goddamnyouryan

+0

@johnnyPando我已經更新了我的答案,並在真正的應用程序中進行了測試,因此現在應該可以正常工作。 – jvperrin

+1

真棒!它做到了。非常感謝。 – goddamnyouryan