简体   繁体   中英

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

If a User has_many Items . And items can be published by setting the :published attribute in items to 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:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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