From e751b8d58ff5088b8dba04b25bc9ae8ac5fd2166 Mon Sep 17 00:00:00 2001
From: David Celis <me@davidcel.is>
Date: Thu, 6 Feb 2014 11:56:39 -0800
Subject: [PATCH] Default values for posts/topics fields on Category

When creating categories (or, at least, subcategories), certain integer
values are set to a default of NULL: topics_week, topics_month,
topics_year, posts_week, posts_month, and posts_year. This causes
consistent exceptions when trying to visit `/categories`, with the
offending line being in
`CategoryDetailedSerializer#count_with_subcategories`. This attempts to
coerce nil into Fixnum.

A fix could be to convert to 0 in the code, but these attributes should
really never be NULL. If there are no posts or topics, they should be 0
to maintain data integrity.

Signed-off-by: David Celis <me@davidcel.is>
---
 ...dd_defaults_to_category_posts_and_topics_fields.rb | 11 +++++++++++
 spec/models/category_spec.rb                          |  8 ++++++++
 2 files changed, 19 insertions(+)
 create mode 100644 db/migrate/20140206195001_add_defaults_to_category_posts_and_topics_fields.rb

diff --git a/db/migrate/20140206195001_add_defaults_to_category_posts_and_topics_fields.rb b/db/migrate/20140206195001_add_defaults_to_category_posts_and_topics_fields.rb
new file mode 100644
index 000000000..28426a572
--- /dev/null
+++ b/db/migrate/20140206195001_add_defaults_to_category_posts_and_topics_fields.rb
@@ -0,0 +1,11 @@
+class AddDefaultsToCategoryPostsAndTopicsFields < ActiveRecord::Migration
+  def change
+    change_column_default :categories, :posts_week,   0
+    change_column_default :categories, :posts_month,  0
+    change_column_default :categories, :posts_year,   0
+
+    change_column_default :categories, :topics_week,  0
+    change_column_default :categories, :topics_month, 0
+    change_column_default :categories, :topics_year,  0
+  end
+end
diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb
index b11dc5db1..11f9e32ca 100644
--- a/spec/models/category_spec.rb
+++ b/spec/models/category_spec.rb
@@ -206,6 +206,14 @@ describe Category do
       @topic.posts.count.should == 1
 
       @category.topic_url.should be_present
+
+      @category.posts_week.should  == 0
+      @category.posts_month.should == 0
+      @category.posts_year.should  == 0
+
+      @category.topics_week.should  == 0
+      @category.topics_month.should == 0
+      @category.topics_year.should  == 0
     end
 
     it "should not set its description topic to auto-close" do