计数器缓存多态多对多关系

时间:2015-09-17 19:01:36

标签: ruby-on-rails activerecord

我想在多对多关联中使用计数器缓存。 一切正常,甚至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

当我从数据库中删除(通过destroy方法)文章时,连接表中的行也会被删除,但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

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我没有ids就加入了桌子(标签)。我不得不从迁移中删除q