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
Written by Vinicius Quaiato
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#