2011-01-27 107 views
0

我正在創建一個條目表單,我希望只有在三個url參數存在時纔可以訪問:example.com/entries/new/2011/01/27如果有人試圖訪問任何其他url(即example.com/entries/newexample.com/entries/new/2011/)我希望Rails設置:提醒並將用戶退回到索引頁面。檢查是否存在多個參數

目前,我只有這個代碼在我的routes.rb match '/entries/new/:year/:month/:day' => 'entries#new'。如果適當的參數不在URL中,我需要做些什麼來控制重定向?我會檢查控制器中的每個參數,然後執行一個redirect_to,或者這是我可以從routes.rb文件專門做的事情嗎?如果是前者,有檢查,所有這三個PARAMS存在其他比一個簡單的方法:

if params[:year].nil && params[:month].nil && params[:day].nil redirect_to ...

+1

您可能得不到很多答案,因爲這不是正常的做事方式。通常,該網址將爲example.com/entries/create?date=2011-01-27或example.com/entries/create?year=2011&month=1&day=27,並且您不會處理所有路由選擇。然後您可以使用驗證來檢查參數。 – 2011-01-28 00:24:22

回答

1

這條路線需要所有三個參數的存在:

match '/entries/new/:year/:month/:day' => 'entries#new' 

由於只有這條路,GET /entries/new將導致:

No route matches "/entries/new" 

您可以從routes.rb這樣的內重定向:

match '/entries' => 'entries#index' 
    match '/entries/new/:year/:month/:day' => 'entries#new' 
    match "/entries/new/(*other)" => redirect('/entries') 

第二行匹配所有三個參數都存在的路徑。第三行使用「路由通配」匹配所有其他/entries/new的情況,並執行重定向。第三行匹配的請求將不會命中EntriesController#new

注意:您可能不需要在第一行,如果你已經定義的路線EntriesController#index - 但要注意resources :entries,這將重新定義indexnew

更多信息可以在指南中找到Rails Routing From the Outside In。在使用日期參數時,限制是一個好主意(第4.2節)