ashr81 - 1 month ago 8

Ruby Question

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`

`UserMark`

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

You have two possibilities.

You can do sorting in Active Record query itself.

```
UserMark.select("math/total as percentage").order('percentage desc')
```

or

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

```
def percentage
self.math/self.total
end
def self.sort_by_percentage
UserMark.all.sort_by(&:percentage).reverse
end
```