[英]What is the best way to count the number of child objects in ActiveRecord
class Foo < ActiveRecord::Base {
has_many :bars
}
foo = Foo.find(1)
foo.bars.count
Is this the best way to count the number of bars or is there an efficient way 这是计算条数的最佳方法还是有效率的方法
If your model is completely normalized then this will be the most efficent way. 如果您的模型已完全规范化,那么这将是最有效的方法。
If you need to do this a lot, you can cache the bars
count on the Foo
table. 如果需要大量执行此操作,则可以在
Foo
表上缓存bars
数。
Railscast Episode 23 covers counter cache, this information is still correct an relevant in the current Rails version. Railscast第23集介绍了计数器缓存,该信息在当前的Rails版本中仍然是正确的。
是的,这是最有效的方法,因为ActiveRecord将其转换为适当的SELECT COUNT(*)SQL语句,这比加载所有记录数据并将它们计数到数组中要高效得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.