diff --git a/app/models/article_follower.rb b/app/models/article_follower.rb index 632f663..a4a8ae1 100644 --- a/app/models/article_follower.rb +++ b/app/models/article_follower.rb @@ -1,5 +1,7 @@ class ArticleFollower < ActiveRecord::Base + attr_accessible :article_id, :person_id, :since - belongs_to :article + belongs_to :article, :counter_cache => :followers_count belongs_to :person + end diff --git a/db/migrate/20150909091347_add_followers_count_to_article.rb b/db/migrate/20150909091347_add_followers_count_to_article.rb new file mode 100644 index 0000000..c5f3648 --- /dev/null +++ b/db/migrate/20150909091347_add_followers_count_to_article.rb @@ -0,0 +1,15 @@ +class AddFollowersCountToArticle < ActiveRecord::Migration + + def self.up + add_column :articles, :followers_count, :integer, :default => 0 + add_column :article_versions, :followers_count, :integer + + execute "update articles set followers_count = (select count(*) from article_followers where article_followers.article_id = articles.id)" + end + + def self.down + remove_column :article_versions, :followers_count + remove_column :articles, :followers_count + end + +end diff --git a/test/fixtures/article_followers.yml b/test/fixtures/article_followers.yml deleted file mode 100644 index 1785b5f..0000000 --- a/test/fixtures/article_followers.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html - -one: - person_id: 1 - article_id: 1 - since: 2015-06-16 17:02:01 - -two: - person_id: 1 - article_id: 1 - since: 2015-06-16 17:02:01 diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 164537e..564af2a 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -2167,4 +2167,21 @@ class ArticleTest < ActiveSupport::TestCase article.destroy end + should "increment followers count when a person follow an article" do + a = fast_create(Article) + p = fast_create(Person) + assert_difference "a.reload.followers_count" do + a.person_followers << p + end + end + + should "decrement followers count when a person unfollow an article" do + p = fast_create(Person) + a = fast_create(Article, :profile_id => p) + a.person_followers << p + assert_difference "a.reload.followers_count", -1 do + a.person_followers.destroy_all + end + end + end -- libgit2 0.21.2