【问题标题】:Counter cache on polymorphic many-to-many relationship多态多对多关系上的计数器缓存
【发布时间】:2015-09-17 19:01:35
【问题描述】:

我想在多对多关联中使用计数器缓存。 一切正常,即使 taggings_count 每次都会增加,但是当关联模型被删除时我遇到了问题。列 taggings_count 未更新。

文章型号:

class Article < ActiveRecord::Base
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings, dependent: :destroy
end

加入表:

class Tagging < ActiveRecord::Base
  belongs_to :tag, counter_cache: true
  belongs_to :taggable, polymorphic: true
end

标签模型:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :articles, through: :taggings, dependent: :destroy
end

当我(通过销毁方法)从数据库中删除一篇文章时,连接表中的行也被删除,但 taggings_count 没有减少。这是输出:

  Article Load (0.2ms)  SELECT  `articles`.* FROM `articles` WHERE `articles`.`slug` = 'test'  ORDER BY `articles`.`id` ASC LIMIT 1
   (0.1ms)  BEGIN
  Tag Load (0.3ms)  SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 29 AND `taggings`.`taggable_type` = 'Article'  ORDER BY `tags`.`taggings_count` DESC
  Tagging Load (0.2ms)  SELECT `taggings`.* FROM `taggings` WHERE `taggings`.`taggable_id` = 29 AND `taggings`.`taggable_type` = 'Article' AND `taggings`.`tag_id` = 26
  SQL (0.2ms)  DELETE FROM `taggings` WHERE `taggings`.`taggable_id` = 29 AND `taggings`.`taggable_type` = 'Article' AND `taggings`.`tag_id` = 26
  SQL (0.2ms)  DELETE FROM `articles` WHERE `articles`.`id` = 29
   (3.5ms)  COMMIT

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:

我解决了这个问题。我有没有 ID 的连接表(标签)。我不得不从迁移中删除 id: false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2021-12-27
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多