Mik*_*ike 4 ruby validation activerecord ruby-on-rails ruby-on-rails-3
我有一个非常安静的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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
check_max_time非常相似.
我知道在控制器中进行验证是违反最佳做法的,但我看不出如何干净地将它添加到模型中.
实际上你正在做的(几乎)best practice并且(几乎)将被合并到Rails 4中strong parametsers.(我说几乎是因为你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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8347 次 |
| 最近记录: |