简体   繁体   English

什么是在ActiveRecord中计算子对象数量的最佳方法

[英]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.

相关问题 当前在Rails ActiveRecord模型中创建父对象时创建子对象的最佳实践是什么? - What's the current best practice for creating child objects on creation of the parent in Rails ActiveRecord models? 基于对象属性获取活动记录对象数组的唯一元素的最佳方法是什么? - What is the best way to get unique elements of an array of activerecord objects based on attributes of the object? 在memcached中存储ActiveRecord对象的最佳方法是什么? - What is the best way to store an ActiveRecord object in memcached? 存储可定位子记录的最佳方法-ActiveRecord | 滑轨 - Best way to store targetable child records - ActiveRecord | Rails 覆盖Rails ActiveRecord销毁行为的最佳方法是什么? - What is the best way to override Rails ActiveRecord destroy behavior? 保存ActiveRecord模型实例的最佳方法是什么? - What's the best way to save an ActiveRecord model instance? 有条件覆盖ActiveRecord删除机制的最佳方法是什么? - What's the best way to conditionally override ActiveRecord's deletion mechanism? 跨两个ActiveRecord行镜像值的最佳方法是什么? - What's the best way to mirror a value across two ActiveRecord rows? 在ActiveRecord模型和观察者中访问路径的最佳方法是什么 - What is the best way of accessing routes in ActiveRecord models and observers 使用Rails和ActiveRecord维护记录的编辑历史记录的最佳方法是什么 - What is the best way to maintain a record's edit history with Rails and ActiveRecord
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM