0

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

The user model has_many :papers and the paper model belongs_to :user

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)

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

Can someone advise me please?

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Slowboy
  • 581
  • 1
  • 7
  • 25

1 Answers1

3

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)')
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • It seems to work, but in the `<%= @heavy_users_testing %>` the Output is displayed as `[#]` I´ve tried to put `.to_f`at the end of the code and also to `@heavy_users_testing` but it gives an error – Slowboy Apr 20 '17 at 09:23
  • It's an array, `pluck` always returns an array. So you would have to do `@heavy_users_testing.first.to_f`, or add `.....pluck(..).first` – Eyeslandic Apr 20 '17 at 09:28
  • Ok I get it, that makes sence, but how is it then possible to get the average of all paper_weight for all users in the Heavy class? The use of `.first` is only showing the first part of the array, right? – Slowboy Apr 20 '17 at 09:41
  • 1
    It's only one value, because it's showing average for all users. That is what you said you wanted. – Eyeslandic Apr 20 '17 at 09:42
  • If you need the average for EACH user, you need to do a `group` – Eyeslandic Apr 20 '17 at 09:43
  • You're right, average for all users is what I wanted and I got it... thanks for the help – Slowboy Apr 20 '17 at 09:46