CounterCache 不适用于多态关联

CounterCache not working for polymorphic association

我正在为我的论坛应用实施 counter_cache 概念。它适用于具有简单 belongs_to 关联但不适用于多态关联的模型。

我的应用程序结构是这样的。我有 3 个模型,论坛,Post 和评论。

class Forum < ApplicationRecord
   has_many :posts
end

Post 型号:

class Post < ApplicationRecord
  belongs_to :forum, counter_cache: true
  has_many :comments, as: :parent
end

评论模型:

class Comment < ApplicationRecord
  belongs_to :parent,polymorphic: true, counter_cache: true
  has_many :comments, as: :parent
end

我的评论模型基本上是一个多态的,所以评论可以属于一个post或者一个评论可以属于另一个评论(这样它会被认为是评论的回复)

我在 Forum 模型中有一个 posts_count 字段,它工作正常并且自动递增和递减正在工作。

我在 Post 模型中也有一个 comments_count 字段。 每当创建新评论时,关联的 Post 中的 comments_count 字段就会递增。 但是当我尝试创建一个评论,其父评论(多态关联)是另一个评论(基本上是对评论的回复)时,我遇到了一个错误:

Started POST "/comments" for 103.255.4.86 at 2018-10-18 20:48:39 +0000
Cannot render console from 103.255.4.86! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by CommentsController#create as JS
  Parameters: {"utf8"=>"✓", "comment"=>{"body"=>"testing a reply", "parent_id"=>"812", "parent_type"=>"Comment"}}
  Post Load (0.8ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" =  LIMIT   [["id", 7], ["LIMIT", 1]]
   (0.4ms)  BEGIN
  Comment Load (1.6ms)  SELECT  "comments".* FROM "comments" WHERE "comments"."id" =  LIMIT   [["id", 812], ["LIMIT", 1]]
  SQL (0.9ms)  INSERT INTO "comments" ("body", "parent_type", "parent_id", "owner_type", "owner_id", "created_at", "updated_at") VALUES (, , , , , , ) RETURNING "id"  [["body", "testing a reply"], ["parent_type", "Comment"], ["parent_id", 812], ["owner_type", "User"], ["owner_id", 46], ["created_at", "2018-10-18 20:48:39.141170"], ["updated_at", "2018-10-18 20:48:39.141170"]]
   (0.4ms)  ROLLBACK
Completed 500  in 43ms (ActiveRecord: 7.2ms)



ActiveModel::MissingAttributeError (can't write unknown attribute `comments_count`):

我在这里错过了什么?任何提示将不胜感激,谢谢!!

我通过从 Comment 模型中删除 counter_cache: true 并在 Comment 模型中定义我自己的计数器递增和递减方法来使其工作。所以这是我的最终 Comment 模型:

class Comment < ApplicationRecord
  belongs_to :parent,polymorphic: true,touch: true
  has_many :comments,dependent: :destroy,as: :parent

  after_create_commit { self.parent_post.increment!(:answers_count,1) }
  after_destroy { self.parent_post.decrement!(:answers_count,1) }

  def parent_post
    (self.parent if parent_type == "Post") || self.parent.parent
  end

end

如果有人想出另一个答案,请post在这里。谢谢。

counter_culture 计数器缓存 gem 原生支持多态关联:https://github.com/magnusvk/counter_culture