Rails和Redis:我应该如何处理验证?

时间:2012-03-08 18:26:07

标签: ruby-on-rails redis

我是铁杆新手。我正在使用Redis而不是使用ActiveRecord支持的东西。我需要验证位置,类别,start_date和end_date的存在。然后我需要检查start_date和end_date是否为有效日期,start_date是否在end_date之前。该位置匹配正则表达式[A-Za-z_]。而那些categories.length> 0.由于我模型的setter中的start_date和end_date参数是Date对象,我应该检查有效日期并在我的控制器中转换它们。然后让我的模型的setter处理其余的验证?

我只是不知道在哪里放置验证:在我的模型或控制器中?

我考虑过创建MyThingieX,MyThingieY和MyThingieZ模型,但是它有点令人困惑,因为.create会创建多个redis键值而不只是一个...注意每个set_方法和“mset”中的for循环”

型号:

class MyThingie
  def self.set_x(location, categories, start_date, end_date, value)
    updates = {}
    for date in (start_date .. end_date)
      # ...
    end

    $redis.mset(*updates.flatten)
  end

  def self.set_y(location, categories, default)
    updates = {}
    for category in categories
      # ...
    end

    $redis.mset(*updates.flatten)
  end

  def self.set_z(location, categories, start_date, end_date, block_category)
    if block_category
      updates = {}
      for date in (start_date .. end_date)
        # ...
      end

      $redis.mset(*updates.flatten)
    else
      deletes = []
      for date in (start_date .. end_date)
        # ...
      end

      $redis.del(*deletes)
    end
  end
end

控制器:

class MyThingieController < ApplicationController
  # ...

  def create
    begin
      method = params[:method]
      location = params[:location]
      categories = params[:categories]
      s_start_date = params[:start_date]
      s_end_date = params[:end_date]

      if method == "normal"
        value = params[:value]

        start_date = Date.strptime(s_start_date, "%m/%d/%Y")
        end_date = Date.strptime(s_end_date, "%m/%d/%Y")

        MyThingie.set_x(location, categories, start_date, end_date, value)
      elsif method == "default"
        default = params[:default]

        MyThingie.set_y(location, categories, default)
      elsif method == "block_category"
        block_category = params[:block_category] == "block_category"

        start_date = Date.strptime(s_start_date, "%m/%d/%Y")
        end_date = Date.strptime(s_end_date, "%m/%d/%Y")

        MyThingie.set_z(location, categories, start_date, end_date, block_category)
      else
        raise "Invalid form submit"
      end
    rescue Exception => e
      errors = [e.message]
      respond_to do |format|
        format.json do
          json = Jsonify::Builder.new
          json.errors errors
          a = json.compile!
          render :status => 400, :json => a
        end
      end
    else
      respond_to do |format|
        format.json do
          json = Jsonify::Builder.new
          json.msg "Update successful."
          a = json.compile!
          render :json => a
        end
      end
    end
  end

这里的键就像

mythingie:location:date = value

mythingie:location:default = default

mythingie:location:date:z =“true”

0 个答案:

没有答案