[英]Getting an average count based on parameters from both the parent and child model
如果User
has_many
Items
。 通过将items中的:published
属性设置为true
可以发布项目。
如何获得创建 项目的 每个用户的平均已发布项目 数 ?
我有一个范围称为“ published
项目,因此您可以通过以下方式获取所有已发布项目:
@items = Item.published
@items = @user.items.published
一种方法是:
avg = Item.published.count.to_f / User.count
编辑:
尝试这个:
@published_items = User.joins(:items).where('items.published = ?', true)
avg = @published_items.count.to_f / @published_items.all(:select => 'distinct users.*').count
要么:
avg = Item.published.count.to_f / User.joins(:items).where('items.published = ?', true).all(:select => 'distinct users.*').count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.