Commit 8093dd0a54d9999d7af3e349605e3509dd8bccbb

Authored by Victor Costa
1 parent d0472735

Add counter cache for article followers

app/models/article_follower.rb
1 1 class ArticleFollower < ActiveRecord::Base
  2 +
  3 + extend CacheCounterHelper
  4 +
2 5 attr_accessible :article_id, :person_id, :since
3   - belongs_to :article
  6 + belongs_to :article, :counter_cache => :followers_count
4 7 belongs_to :person
  8 +
  9 + after_create do |article_follower|
  10 + ArticleFollower.update_cache_counter(:followers_count, article_follower.article, 1)
  11 + end
  12 +
  13 + after_destroy do |article_follower|
  14 + ArticleFollower.update_cache_counter(:followers_count, article_follower.article, -1)
  15 + end
5 16 end
... ...
db/migrate/20150909091347_add_followers_count_to_article.rb 0 → 100644
... ... @@ -0,0 +1,15 @@
  1 +class AddFollowersCountToArticle < ActiveRecord::Migration
  2 +
  3 + def self.up
  4 + add_column :articles, :followers_count, :integer, :default => 0
  5 + add_column :article_versions, :followers_count, :integer
  6 +
  7 + execute "update articles set followers_count = (select count(*) from article_followers where article_followers.article_id = articles.id)"
  8 + end
  9 +
  10 + def self.down
  11 + remove_column :article_versions, :followers_count
  12 + remove_column :articles, :followers_count
  13 + end
  14 +
  15 +end
... ...