0
votes

I am working on mongoDB with Rails. So using gem mongoid, Anyone know how to validate Hash fields in model?

2
@apneadiving : Actually i went through this link before and came to know that the only way is custom validation. Any how, Thank you for the reply.Jyothu
That was the answer, yes :)apneadiving

2 Answers

0
votes
0
votes

Looking for a solution, I came to a custom validator that appears good to me and it can be used generically.

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

Let's suppose we have this field:

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

Actually, it's not a validator, it's a callback. It works like this:

before_save :fieldname_fix_content

Under 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