【问题标题】:Using .average with .pluck in ruby on rails app?在 ruby​​ on rails 应用程序中使用 .average 和 .pluck?
【发布时间】:2017-04-20 17:44:53
【问题描述】:

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

user 模型 has_many :paperspaper 模型 belongs_to :user

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

我不知道除了active record .average 可以在哪里获取Heavy 类别用户的平均Officepaper 重量吗?

有人可以给我建议吗?

【问题讨论】:

  • 您需要所有用户的平均值还是每个用户的平均值?
  • 我需要 officepaper 类型的平均纸张重量,适用于所有具有 indusrty_type Heavy 的用户

标签: ruby-on-rails activerecord


【解决方案1】:

你可以使用pluck里面的sql avg函数

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

如果你想要/需要每个用户的平均值,你需要做一个group

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

【讨论】:

  • 它似乎可以工作,但在<%= @heavy_users_testing %> 中,输出显示为[#<BigDecimal:7ffa497d5f50,'0.15E2',9(27)>] 我试图将.to_f 放在代码的末尾以及@heavy_users_testing 但它给出一个错误
  • 它是一个数组,pluck 总是返回一个数组。所以你必须做@heavy_users_testing.first.to_f,或者添加.....pluck(..).first
  • 好的,我明白了,这是有道理的,但是如何才能获得 Heavy 类中所有用户的所有 paper_weight 的平均值? .first 的使用只是显示数组的第一部分,对吧?
  • 这只是一个值,因为它显示了所有用户的平均值。这就是你所说的你想要的。
  • 如果你需要每个用户的平均值,你需要做一个group
猜你喜欢
  • 2014-11-05
  • 1970-01-01
  • 2011-05-15
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 2019-07-24
相关资源
最近更新 更多