Rails Modeling Columns of a Counter_cache Column

I use rspec for testing and hornsby scripts for graphing objects used in tests.

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

+3
source share
2 answers

Yes, you must set the default value. Otherwise, special mathematical operations must be performed to process NULL.

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

@posts.sum(&:comment_count), , , nil.

:

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

+8

SQL

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

, , undefined +1 == 1, Rails . , . , ( ), . , , .

+1

Source: https://habr.com/ru/post/1718153/


All Articles