gpt4 book ai didi

ruby-on-rails - Mongoid 和 counter_cache 列

转载 作者:行者123 更新时间:2023-12-01 09:27:55 24 4
gpt4 key购买 nike

我有评论模型:

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 method
count' for nil:NilClass

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

最佳答案

完整的解决方案供以后引用:

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

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

关于ruby-on-rails - Mongoid 和 counter_cache 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19942190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com