Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
FastIndian Avatar asked May 07 '26 02:05

FastIndian


2 Answers

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.

like image 199
David Backeus Avatar answered May 11 '26 14:05

David Backeus


Sloved with:

counter_cache: :comments_count

like image 41
FastIndian Avatar answered May 11 '26 16:05

FastIndian