鉴于Mongoid模型:
class Counts
include Mongoid::Document
# lists of tag counts
field :tags, type: Hash, default: {}
end
c = Counts.new( tags = {new: 12, old: 7})
我想覆盖c#tags[]
,以便如果未在tags
字段上设置密钥,则应返回0
而不是nil
的默认值像这样:
c.tags['ancient']
# => 0
答案 0 :(得分:1)
尝试设置默认哈希值,如下所示:
class Counts
...
field :tags, type: Hash, default: Hash.new{ |h, k| h[k] = 0 }
end