Rails validating search parameters

I have an API that is pretty reassuring, but I'm struggling to figure out how to do the search. I want to be able to search all records between two dates, time dates can be no more than 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_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 is pretty similar.

I know this against best practices for checking in the controller, but I don’t see how I can add it to the model.

+3
source share
3 answers

, () 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
+5

. , API Grape, , .

+1

, , , .

class SearchController < ApplicationController
  before_filter :assign_default_params

  def index
  end

  private
  def assign_default_params
    params[:start_time] ||= Time.now
    params[:end_time]   ||= params[:start_time] + 6.hours
    params[:end_time]     = params[:start_time] + 6.hours if ((params[:end_time] - params[:start_time]) / 3600).round) > 6
  end
end

Using this code above, it always has the parameters needed to search. The method assign_default_paramstries to assign default values ​​if they are not sent from clients. The last thing he does is that he assigns the params[:end_time]maximum value.

This is a lot neat because we don’t need to do the verification, and the client does not need to process another response code, for example 422. And you should have API documentation that talks about this fact.

0
source

All Articles