Commit 839b1002122fb949a6ec2ba3a13217350d3b0c52

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 2 attr_accessible :article_id, :person_id, :since
3   - belongs_to :article
  3 + belongs_to :article, :counter_cache => :followers_count
4 4 belongs_to :person
  5 +
  6 + after_create do |article_follower|
  7 + ArticleFollower.update_cache_counter(:followers_count, article_follower.article, 1)
  8 + end
  9 +
  10 + after_destroy do |article_follower|
  11 + ArticleFollower.update_cache_counter(:followers_count, article_follower.article, -1)
  12 + end
5 13 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
... ...