Mongoid Hash字段访问器的默认值

时间:2016-09-19 15:36:17

标签: ruby-on-rails hashmap mongoid activesupport

鉴于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

1 个答案:

答案 0 :(得分:1)

尝试设置默认哈希值,如下所示:

class Counts
  ...
  field :tags, type: Hash, default: Hash.new{ |h, k| h[k] = 0 }
end