在Rails应用程序中在Ruby中使用.average和.pluck? [英] Using .average with .pluck in ruby on rails app?

查看:57
本文介绍了在Rails应用程序中在Ruby中使用.average和.pluck?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我想查看注册到 Heavy 类的用户的平均纸张使用重量。

In my app I want to see the average paper use weight for my users which registers to the Heavyclass.

用户模型 has_many:papers 纸张模型 belongs_to:user

这是我得到的到目前为止: @heavy_users_testing = User.where(industry_type:'Heavy')。joins(:papers).where( papers.paper_type ='Officepaper')。pluck(:paper_weight)

here is what I got so far: @heavy_users_testing = User.where(industry_type: 'Heavy').joins(:papers).where("papers.paper_type = 'Officepaper'").pluck(:paper_weight)

我不确定要去哪里,但是活动记录.average 可以得到平均的Officepaper

I'm not sure where to but the active record .average to get the average Officepaper weight for users in the Heavy category?

有人可以建议我吗?

推荐答案

您可以在<$ c $中使用sql avg 函数c> pluck

You can use the sql avg function inside pluck

@heavy_users_testing = User.where(industry_type: 'Heavy')
  .joins(:papers)
  .where(papers: { paper_type: 'Officepaper' } )
  .pluck('avg(paper_weight)')

如果您希望/需要每个用户的平均值,则需要进行

If you want/need the average for EACH user, you need to do a group

@heavy_users_testing = User.where(industry_type: 'Heavy')
  .joins(:papers)
  .where(papers: { paper_type: 'Officepaper' } )
  .group(:user_id)
  .pluck('avg(paper_weight)')

这篇关于在Rails应用程序中在Ruby中使用.average和.pluck?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆