Rails 模型 counter_cache 列初始化

发布于 2024-08-05 11:36:23 字数 126 浏览 2 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心清如水 2024-08-12 11:36:23

是的,您应该设置默认值。否则,您必须进行特殊情况的数学运算来处理 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

奶气 2024-08-12 11:36:23

Rails 只需发送以下 SQL

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

,因此数据库要么知道 undefined +1 == 1,要么 Rails 自己进行一些初始化。
在任何一种情况下,这对我来说都是稳定的行为,所以不要将它们设置为零并保存工作。因为无论如何你都无法看到你是否进行了初始化(没有初始化它的工作原理是一样的)你将如何测试它。如果它不能保证由您初始化,那么您在未来的证明方面真正获得了什么。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文