在我的Rails應用程序中,我想驗證filter
和post_type
參數。在Rails中驗證參數
兩者都是可選的,但如果它們存在,它們必須具有值並且必須具有與有效值數組中的值匹配的值。
在我的控制器我有檢查他們兩個方法:
def validate_filter
if params.has_key?(:filter)
if params[:filter].present?
if ['popular', 'following', 'picks', 'promoted', 'first-posts'].include?(params[:filter])
return true
else
return false
end
else
return false
end
else
return true
end
end
def validate_post_type
if params.has_key?(:post_type)
if params[:post_type].present?
if ['discussions', 'snaps', 'code', 'links'].include?(params[:post_type])
return true
else
return false
end
else
return false
end
else
return true
end
end
然後在我的主控制器的方法我做的:
def index
raise ActionController::RoutingError.new('Not Found') unless validate_filter && validate_post_type
...
因此,這意味着post_type=
和post_type=cam
將返回404,但post_type=snaps
將返回true。
有沒有更好的方法來驗證傳遞的params是否有效,但是這兩個參數都是空的,如果key本身存在。在這種情況下僅使用blank?
和present?
是不夠的。
如果應用程序使用RESTAPI然後嘗試使用[JSON-架構(https://github.com/ruby-json-schema/json-schema),而不是這樣的情況下,自定義的驗證。 –