FastIndian
FastIndian

Reputation: 242

Mongoid and counter_cache column

I have Comment model:

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps
  belongs_to :commentable, polymorphic: true, touch: true#, counter_cache: true

When I run:

Article.first.comments.count => 1 #without counter_cache: true

but with "counter_cache: true" I get :

Article.first.comments.count => NoMethodError: undefined method count' for nil:NilClass Article.first.comments => NoMethodError: undefined methodcount' for nil:NilClass

Has anyone encountered such problem?

Upvotes: 3

Views: 2406

Answers (3)

Feuda
Feuda

Reputation: 2365

As with ActiveRecord, the :counter_cache option can be used on an association to make finding the number of belonging objects more efficient. Also similar to ActiveRecord, you must take into account that there will be an extra attribute on the associated model. This means that with Mongoid, you need to include Mongoid::Attributes::Dynamic on the associated model

https://www.mongodb.com/docs/mongoid/8.0/reference/associations/index.html#the-counter-cache-option

Upvotes: 0

David Backeus
David Backeus

Reputation: 469

The complete solution for future reference is:

class Comment
  include Mongoid::Document
  belongs_to :commentable, polymorphic: true, touch: true, counter_cache: :comments_count
 end

class Article
  include Mongoid::Document
  field :comments_count, type: Integer
end

So don't forget to add the integer field to the parent model.

Upvotes: 6

FastIndian
FastIndian

Reputation: 242

Sloved with:

counter_cache: :comments_count

Upvotes: 2

Related Questions