Mongoid和counter_cache列

时间:2013-11-12 23:31:54

标签: ruby-on-rails mongoid counter-cache

我有评论模型:

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:未定义的方法count' for nil:NilClass Article.first.comments => NoMethodError: undefined method count'为nil:NilClass

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:2)

解决:

counter_cache :: comment_count