views:

261

answers:

2

I'm using rspec for testing and hornsby scenarios for object graphs used in tests.

Is it good practice to initialize counter cache columns to 0 value instead of leaving them uninitialized (nil)? Or should i define default value in migrations that create those counter cache columns?

+2  A: 

Rails simply send the following SQL

UPDATE posts SET comment_count = comment_count + 1, WHERE id IN (10, 15)

So either the DB knows that undefined +1 == 1 or Rails does some initialization of its own. In either case this seems like stable behavior to me, so don't set them to zero and save the work. Since you will not be able to see if you did the initialization anyway (it works just the same without) how will you test it. And if it is not guaranteed to be initialized by you what have you really gained in terms of future proofing.

nasmorn
+1  A: 

Yes, you should set the default value. Otherwise you have to special case math operations to handle NULLs.

Let's say you had an array of post objects and you wanted to get sum the number of comments.

If you initialize to zero @posts.sum(&:comment_count) will, but if you don't it might not because it will fail on nil.

I recommend defining your column like this:

add_column :posts, :comments_count, :integer, :default => 0, :null => false

Luke Francl