Rails的验证搜索PARAMS [英] Rails validating search params

查看:146
本文介绍了Rails的验证搜索PARAMS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,这是相当宁静,但我在努力工作,如何简洁地实现搜索。我希望能够搜索两个日期倍之间的所有记录,日期 - 时间允许最大为6小时的间隔。目前,在我的控制器方法,我有以下几点:

I have an API which is fairly restful but am struggling to work out how to implement a search cleanly. I want to be able to search for all the records between two date-times, the date-times are allowed to be a maximum of 6 hours apart. At the moment in my controller method I have the following:

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是看起来像这样的应用方法:

check_required_params is an application method that looks like this:

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是相当类似的。

check_max_time is fairly similar.

我知道这是对最佳实践做检验的控制器,但我不知道怎样才能把它添加到模型干净。

I know it's against best practices to do validation in the controller but I can't see how I can add it to the model cleanly.

推荐答案

其实,你在做什么是(几乎)<$​​ C $ C>最佳实践,将(几乎)在Rails中被纳入4 强parametsers 。 (我说的差不多,因为你的 check_max_time 看起来应该是在模型验证。)

Actually what you are doing is (almost) best practice and will (almost) be incorporated in Rails 4 with strong parametsers. (I say almost because your check_max_time looks like it should be a validation in your model.)

您应该继续前进,在功能,今天拉,使升级变得更容易对自己。强大的参数 https://github.com/rails/strong_parameters

You should go ahead and pull in the feature today and make upgrades easier on yourself. Strong Parameters https://github.com/rails/strong_parameters

文件是存在的,但在这里是你如何将它。

Documentation is there, but here is how you incorporate it.

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

这篇关于Rails的验证搜索PARAMS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆