Rails类方法验证

时间:2015-10-20 07:05:03

标签: ruby-on-rails activerecord

我有一些类方法可以帮助查询数据库,但是我想为发送给这些方法的参数添加某种验证。例如,

def self.get_ayahs_by_range(surah_id, from, to)
      self.where('quran.ayah.surah_id = ?', surah_id)
          .where('quran.ayah.ayah_num >= ?', from)
          .where('quran.ayah.ayah_num <= ?', to)
          .order('quran.ayah.surah_id, quran.ayah.ayah_num')
    end

通过将params[:surah_id]params[:to]params[:from]传递给此函数从控制器调用。

有时,出于某种原因,我们:surah_idundefined会造成混乱。如何通过之前的验证来解决?

对于除了strong_params之外的params验证的任何建议,我觉得这对于索引操作不起作用?

控制器:

def index
    unless valid_params?
      return render json: {message: 'Params are wrong.'}
    end

    params_hash = (params[:range] || ("#{params[:from]}-#{params[:to]}")) + "/#{params[:quran]}/#{params[:audio]}/#{params[:content]}"

    if params.key?(:range)
      range = params[:range].split('-')
    elsif params.key?(:from) && params.key?(:to)
      range = [params[:from], params[:to]]
    else
      range = ['1', '10']
    end

    if (range.last.to_i - range.first.to_i) > 50
      return render json: {error: "Range invalid, use a string (maximum 50 ayat per request), e.g. '1-3'"}
    end

    @results = Rails.cache.fetch("surahs/#{params[:surah_id]}/ayahs/#{params_hash}", expires_in: 12.hours) do
      ayahs = Quran::Ayah.get_ayahs_by_range(params[:surah_id], range[0], range[1])
      Quran::Ayah.merge_resource_with_ayahs(params, ayahs)
    end

    render json: @results
  end

1 个答案:

答案 0 :(得分:1)

在模型中创建一个新的简单类(它不必是数据库中的表)

require 'ostruct'
class SearchOptions < OpenStruct
  include ActiveModel::Validations
  validates :surah_id, presence: true
  validates :from, presence: true
  ...
end

然后在控制器中

@search_option = SearchOption.new(seach_params)
@search_option.valid?
   # here you put the "invalid" processing
   # maybe re-render the search parameters view
end