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"
endand
create_table "courses", force: :cascade do |t| t.integer "course_number" t.float "gpa"
endI want to calculate the average gpa: current_gpa = sum of gpa of courses taken / num of course taken. How can I do this?
13 Answers
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 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 You can use ActiveRecord::Calculations average:
profile.courses.average(:gpa)