ashr81 ashr81 - 10 months ago 56
Ruby Question

Is it possible to sort based on an arthimatic operation in Ruby on rails active record?

I want to order records based on two columns Arthimatic operation.

Ex: I has table columns on which I has to do an arthimatic operation and sort based on its value.
Let the columns be

math, science and total
.And table name is
Typically my query looks like this

UserMark.order('(math/total) desc')

This should order the UserMarks based on math/total operation.How could it be done in Ruby on rails?

Answer Source

You have two possibilities.

You can do sorting in Active Record query itself."math/total as percentage").order('percentage desc')


You can do it in ruby method (this method should be in your model).

def percentage

def self.sort_by_percentage