2015-11-11 34 views
0

驗證模型中沒有的url參數的最佳方法是什麼?驗證在模型中的Rails 4中的url params不在

具體來說,我有一個路線如下圖所示:

get 'delivery_windows/:date', 
     to: 'delivery_windows#index', 
     :constraints => { :date => /\d{4}-\d{2}-\d{2}/ }, 
     as: :delivery_windows 

我想確保:日期是有效的日期和正則表達式是不是一個解決方案。日期不能在過去,並且不超過3個月。

預先感謝您

+0

是不是很容易,只需發佈​​日期爲GET變種?比如delivery_windows?date = xxxx-xx-xx,你可以用params [:date]輕鬆檢查。 –

回答

0

感謝解決者和sadaf2605的迴應。

我最終通過使用before_action並在那裏引發了一個路由錯誤來結合他們的建議。

在我的控制器我說:

class AngularApi::V1::DeliveryWindowsController < ApplicationController 
    before_action :validate_date_param, only: :index 

    def index 
    ... 
    end 

    private 

    def validate_date_param 
    begin 
     Date.parse(params[:date]) 
    rescue ArgumentError 
     render json: [{ 
     param: :date, 
     message: "Incorrect Date Format: Date format should be yyyy-mm-dd." 
     }].to_json, status: :unprocessable_entity 
     return 
    end 
    end 
end 
2

雖然我不知道我會在路由層處理這個問題我自己,你應該能夠使用Advanced Routing Constraints這一點。

這個想法是,constraints可以接受一個響應matches?的對象。如果matches?返回true,則約束通過,否則約束失敗。一個簡單的實現,這將是如下:

在你config/routes.rb,包括像這樣:

require 'routing/date_param_constraint' 

get 'delivery_windows/:date', 
    to: 'delivery_windows#index', 
    constraints: DateParamConstraint, 
    as: :delivery_windows 

然後,在某處你的應用程序(也許在lib/routing/date_param_constraint.rb),定義一個類像下面這樣:

module DateParamConstraint 
    def matches?(request) 
    # Check `request.parameters[:date]` to make sure 
    # it is valid here, return true or false. 
    end 
end 
+0

你會說哪裏是正確的地方來處理這個錯誤,以及如何? – Sina

+0

我可能會用'before_action'在控制器中處理它,主要是因爲作爲用戶,當我指定一個無效參數時,我希望得到更有用的消息。例如,如果我指定的日期超出範圍,我希望我會被告知,而不是得到一種通用的404響應。 – theunraveler

0

那麼您可以在控制器中過濾日期,並在您獲取不符合要求的日期時提升404 not found

def show 
    date=params[:date].strftime("%Y-%m-%d').to_date 
    if date > 0.day.ago or date > 3.month.from_now 
     raise ActionController::RoutingError.new('Not Found') 
    end 
end