Rails 模型 counter_cache 列初始化
我使用 rspec 进行测试,并使用 Hornsby 场景来测试测试中使用的对象图。
将计数器缓存列初始化为 0 值而不是让它们保持未初始化 (nil) 是一个好习惯吗?或者我应该在创建这些计数器缓存列的迁移中定义默认值?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您应该设置默认值。否则,您必须进行特殊情况的数学运算来处理 NULL。
假设您有一个帖子对象数组,并且想要获得评论数量的总和。
如果你初始化为零,
@posts.sum(&:comment_count)
会,但如果你不这样做,它可能不会,因为它会在 nil 时失败。我建议像这样定义您的列:
add_column :posts, :comments_count, :integer, :default => 0,:空=>错误
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
Rails 只需发送以下 SQL
,因此数据库要么知道 undefined +1 == 1,要么 Rails 自己进行一些初始化。
在任何一种情况下,这对我来说都是稳定的行为,所以不要将它们设置为零并保存工作。因为无论如何你都无法看到你是否进行了初始化(没有初始化它的工作原理是一样的)你将如何测试它。如果它不能保证由您初始化,那么您在未来的证明方面真正获得了什么。
Rails simply send the following SQL
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.