简体   繁体   English

根据父模型和子模型的参数获取平均计数

[英]Getting an average count based on parameters from both the parent and child model

If a User has_many Items . 如果User has_many Items And items can be published by setting the :published attribute in items to true . 通过将items中的:published属性设置为true可以发布项目。

How do I get the average number of published items , per user that created an item? 如何获得创建 项目的 每个用户平均发布项目

I have a scope for items called published , so you can get all published items by writing: 我有一个范围称为“ published项目,因此您可以通过以下方式获取所有已发布项目:

@items = Item.published
@items = @user.items.published

One way is: 一种方法是:

   avg = Item.published.count.to_f / User.count

EDIT: 编辑:

Try this: 尝试这个:

  @published_items = User.joins(:items).where('items.published = ?', true)
  avg = @published_items.count.to_f / @published_items.all(:select => 'distinct users.*').count

Or: 要么:

  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM