【问题标题】:Validation Hash fields using mongoid使用 mongoid 验证哈希字段
【发布时间】:2012-11-30 11:13:17
【问题描述】:

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

【问题讨论】:

  • 真正的答案在这里:github.com/mongoid/mongoid/issues/1563
  • @apneadiving :实际上我之前浏览过这个链接并且知道唯一的方法是自定义验证。不管怎样,谢谢你的回复。
  • 答案是肯定的 :)

标签: ruby-on-rails validation hash mongoid


【解决方案1】:

我们必须编写自定义验证方法

Here explained how we are writing custom validation methods

【讨论】:

    【解决方案2】:

    在寻找解决方案时,我找到了一个对我来说很好并且可以通用的自定义验证器。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2016-07-19
      • 2014-01-04
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      相关资源
      最近更新 更多