我有一个相当安静的 API,但正在努力弄清楚如何干净地实现搜索。我希望能够搜索两个日期时间之间的所有记录,日期时间最多允许相隔 6 小时。目前在我的控制器方法中我有以下内容:
required_params = [:start_time, :end_time]
if check_required_params(required_params, params) and check_max_time_bound(params, 6.hours)
... rest of controller code here ...
end
check_required_params 是一个应用程序方法,如下所示:
def check_required_params(required_params, params_sent)
required_params.each do |param|
unless has_param(param, params_sent)
unprocessable_entity
return false
end
end
true
end
check_max_time 非常相似。
我知道在控制器中进行验证是违反最佳实践的,但我不知道如何将其干净地添加到模型中。
实际上你正在做的是(几乎)best practice
并将(几乎)合并到 Rails 4 中strong parametsers
。 (我说几乎是因为你check_max_time
看起来它应该是您模型中的验证。)
您应该立即加入该功能,让自己更轻松地进行升级。参数强https://github.com/rails/strong_parameters https://github.com/rails/strong_parameters
文档就在那里,但以下是合并它的方法。
class SearchController < ApplicationController
include ActiveModel::ForbiddenAttributesProtection
def create
# Doesn't have to be an ActiveRecord model
@results = Search.create(search_params)
respond_with @results
end
private
def search_params
# This will ensure that you have :start_time and :end_time, but will allow :foo and :bar
params.require(:start_time, :end_time).permit(:foo, :bar #, whatever else)
end
end
class Search < ActiveRecord::Base
validates :time_less_than_six_hours
private
def time_less_than_six_hours
errors.add(:end_time, "should be less than 6 hours from start") if (end_time - start_time) > 6.hours
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)