caffeinated.tech
caffeinated.tech

Reputation: 6548

Default value for Mongoid Hash field accessor

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

Answers (1)

Jagdeep Singh
Jagdeep Singh

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

Related Questions