[英]Validate url params not in model in Rails 4
What is the best way to validate url params that are not in the model. 验证模型中没有的url参数的最佳方法是什么。
Specifically I have a route like below: 具体来说,我的路线如下:
get 'delivery_windows/:date',
to: 'delivery_windows#index',
:constraints => { :date => /\d{4}-\d{2}-\d{2}/ },
as: :delivery_windows
I want to make sure that :date is a valid date and regex is not a solution. 我想确保:date是有效日期,而regex不是解决方案。 the date cant be in the past and not more than 3 months into the future. 日期不能是过去的日期,也不能是未来的3个月以内。
Thank you in advance 先感谢您
While I'm not sure that I would handle this in the routing layer myself, you should be able to use Advanced Routing Constraints for this. 虽然我不确定自己会在路由层中处理此问题,但是您应该可以使用“ 高级路由约束 ”。
The idea is that constraints
can accept an object that responds to matches?
这个想法是constraints
可以接受响应matches?
的对象matches?
. 。 If matches?
如果matches?
returns true, then the constraint passes, otherwise, the constraint fails. 返回true,则约束通过,否则约束失败。 A simple implementation of this would be the following: 一个简单的实现如下:
In your config/routes.rb
, including something like this: 在您的config/routes.rb
,包括以下内容:
require 'routing/date_param_constraint'
get 'delivery_windows/:date',
to: 'delivery_windows#index',
constraints: DateParamConstraint,
as: :delivery_windows
Then, somewhere in your application (perhaps in lib/routing/date_param_constraint.rb
), define a class like the following: 然后,在应用程序中的某个位置(可能在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
Well you can filter your date at controller, and raise 404 not found
when you get date that does not fulfil your requirement. 好了,您可以在控制器上过滤日期,并在获取不满足要求的日期时加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
Thanks to theunraveler and sadaf2605 for their responses. 感谢theunraveler和sadaf2605的回应。
I ended up doing to combination of their suggestions by using the before_action and raising a routing error in there. 我最终通过使用before_action并在那里提出路由错误来将他们的建议组合在一起。
in my controller I added: 在我的控制器中,我添加了:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.