3

我有评论模型:

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

当我运行时:

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

但是使用“counter_cache:true”我得到:

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

有没有人遇到过这样的问题?

4

2 回答 2

6

供将来参考的完整解决方案是:

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

所以不要忘记将整数字段添加到父模型中。

于 2015-03-24T10:27:25.157 回答
2

喜欢:

counter_cache: :comments_count

于 2013-11-13T22:48:20.390 回答