Calculate average of column value in Ruby on Rails

ruby array average
rails group by sum
rails group count
activerecord count
rails activerecord group by column
active record group by
activerecord calculated fields
rails select query

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?

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

average (ActiveRecord::Calculations), In Rails 3 the returned value will be type cast to the column's type and not Float. So when calculating average on a column the column's type need to be float, the​  Rails’ Active Record does include an #average method. It’s used to perform calculations on numerical columns in the database directly in SQL. If that is your specific use case, you should definitely use that method. Instantiating Active Record models and subsequently iterating over the Array in Ruby will nearly always be slower.

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

ActiveRecord::Calculations, average(column_name, options = {}). Calculates the average value on a given column. Returns nil if there's no row. See calculate for  This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query. There are two basic forms of output: * Single aggregate value: The single value is type cast to Fixnum

You can use ActiveRecord::Calculations average:

profile.courses.average(:gpa)

Calculate a mean average from a Ruby array, Ruby doesn't provide a native method to generate an average (mean) value from an Array#sum when calculating the mean average from an array of integers: Rails' Active Record does include an #average method. It's used to perform calculations on numerical columns in the database directly in SQL. In Rails 3 the returned value will be type cast to the column’s type and not Float. So when calculating average on a column the column’s type need to be float, the result will be truncated otherwise.

Ruby on Rails/ActiveRecord/Calculations, AverageEdit. You can use the average method to calculate the average value for a particular column. For example: This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. Person.calculate(:count, :all) # The same as Person.count Person.average(:age) # SELECT AVG(age) FROM people

How to calculate average and sum of a field with filters using mongo , How to calculate average and sum of a field with filters using mongo in ruby. We talk about two queries in mongo to calculate average and sum for a given field with option to add How to update a column directly in Database in Ruby on Rails. This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. There are two basic forms of output: * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column 's type for everything else. * Grouped values: This

#6103 average() returns integer values instead of decimals, t.comments.calculate(:average, 'rating') => 4 rails install and sqlite3, and the calculated value is different for columns of type integer and float. This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. There are two basic forms of output: * Single aggregate value: The single value is type cast to Integer for COUNT, Float for AVG, and the given column's type for everything else.

Comments
  • Any error messages? Please post those. It is best to show some effort in your questions otherwise they are in jeopardy of not being well received.