Reputation: 6548
Given a Mongoid model:
class Counts
include Mongoid::Document
# lists of tag counts
field :tags, type: Hash, default: {}
end
c = Counts.new( tags = {new: 12, old: 7})
I would like to override c#tags[]
so that if a key isn't set on the tags
field, it should return a default of 0
instead of nil
like this:
c.tags['ancient']
# => 0
Upvotes: 0
Views: 573
Reputation: 4920
Try setting default hash values as below:
class Counts
...
field :tags, type: Hash, default: Hash.new{ |h, k| h[k] = 0 }
end
Upvotes: 1