Last Updated: February 25, 2016
·
2.379K
· vquaiato

mongoid counter_cache

Instead of creating several callbacks in the mongoid models use the counter_cache feature.

class Foo
    include Mongoid::Document

    has_many :bars
    field :bars_count, type: Fixnum, default: 0
end

class Bar
    include Mongoid::Document

    belongs_to :foo, counter_cache: true
end

Simply adding the counter_cache: true on the relation will create all the necessary things to you. Then:

f = Foo.create
b = Bar.create(foo: f)

f.bars_count #should be 1