I would like to have counter cache on many-to-many association. Everything works fine, even taggings_count is increment every time, but I have a problem when associated model is removed. The column taggings_count isn't updated.
Article model:
class Article < ActiveRecord::Base
has_many :taggings, as: :taggable
has_many :tags, through: :taggings, dependent: :destroy
end
join table:
class Tagging < ActiveRecord::Base
belongs_to :tag, counter_cache: true
belongs_to :taggable, polymorphic: true
end
Tag model:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings, dependent: :destroy
end
When I remove (by destroy method) an article from database, row from join table is removed as well, but no decrement on taggings_count. Here is the output:
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