gpt4 book ai didi

ruby-on-rails - Rails 验证搜索参数

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:08 27 4
gpt4 key购买 nike

我有一个相当安静的 API,但我正在努力弄清楚如何干净地实现搜索。我希望能够搜索两个日期时间之间的所有记录,日期时间最多可以相隔 6 小时。目前在我的 Controller 方法中我有以下内容:

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_pa​​rams 是一个应用方法,看起来像这样:

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 非常相似。

我知道在 Controller 中进行验证是违反最佳实践的,但我看不出如何将它干净地添加到模型中。

最佳答案

实际上,您所做的(几乎)是最佳实践,并且(几乎)将通过强大的参数合并到 Rails 4 中。 (我说几乎是因为你的 check_max_time 看起来应该是你模型中的验证。)

您今天应该继续使用该功能,让自己更轻松地进行升级。强参数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

关于ruby-on-rails - Rails 验证搜索参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10745814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com