matthewng
matthewng

Reputation: 59

Calculate average of column value in Ruby on Rails

I'm kind of new to Ruby on Rails. I have a profile model which has_many courses taken.

create_table "profiles", force: :cascade do |t|
   t.string   "pname"
   t.float    "current_gpa"
end

and

create_table "courses", force: :cascade do |t|
   t.integer  "course_number"
   t.float    "gpa"
end

I want to calculate the average gpa: current_gpa = sum of gpa of courses taken / num of course taken. How can I do this?

Upvotes: 2

Views: 10731

Answers (3)

Michael Wiltbank
Michael Wiltbank

Reputation: 141

An additional note here... Average returns floating point numbers or BigDecimal which is often represented in decimal notation. This can be confusing and may not be what you are looking for. You might explore adding something like: .to_int, .to_f, .truncate, .round, etc...

Person.average(:age) # => 0.387e2
Person.average(:age).to_i # => 38
Person.average(:age).to_f # => 38.7
Person.average(:age).to_f.round # => 39

Upvotes: 6

dp7
dp7

Reputation: 6749

You can use ActiveRecord::Calculations average:

profile.courses.average(:gpa)

Upvotes: 0

trh
trh

Reputation: 7339

You should consider reading some documentation - obviously it's quick to get a answer on SO but sometimes the docs can lead you to something you didn't know to look for or ask for.

That said, the fastest way is to use average

profile.courses.average(:gpa)

This will give you an average. Or you can do it the long way, if for some reason you need make modifications in between.

profile.courses.sum(:gpa) / profile.courses.count

Upvotes: 14

Related Questions