2012-11-30 45 views
0

我正在使用Rails的mongoDB。所以使用gem mongoid,任何人都知道如何验证模型中的哈希字段?验证哈希字段使用mongoid

+1

真正的答案在这里:https://github.com/mongoid/mongoid/issues/1563 – apneadiving

+0

@apneadiving:其实我通过这个环节去之前,才知道唯一的方法就是自定义验证。任何如何,谢谢你的答复。 – Jyothu

+0

这就是答案,是的:) – apneadiving

回答

0

寻找一个解决方案,我来出现对我好自定义验证程序,它可以使用一般。

private 
def fix_content(input_hash, valid_fields) 
    temphash = {} 
    input_hash.each do |k,v| 
     k=k.to_sym 
     if valid_fields.has_key? k 
      case valid_fields[k] 
       when 'integer' 
        v=v.to_i 
       when 'boolean' 
        v=(v=='true' || v==true) 
       when 'float' 
        v=v.to_f 
       when 'array' 
        v = "#{v.class}"=="Array" ? v : [] 
       else 
        v=v.to_s 
      end 
      temphash[k]=v 
     end 
    end 
    temphash 
end 

让我们假设我们有这样的领域:

field :fieldname, type: Hash, default: {hfield1: 0, hfield2: [], hfield3: false} 

其实,它不是一个验证器,这是一个回调。它的工作原理是这样的:

before_save :fieldname_fix_content 

private

def fieldname_fix_content 
    # we show the callback what fields will be processed. All others will be disposed of 
    self.fieldname = fix_content(self.fieldname, {:hfield1=> 'integer', :hfield2=>'array', :hfield3=>'boolean'}) 
end