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?
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.
Sloved with:
counter_cache: :comments_count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With