Perform custom calculation on model and sort by the calculation

Hi,

If anyone can point me in the right direction, I'd very appreciative.

I need to peform a calculation on a model (a number of columns) and use a few columns of the model of the person who is logged in. Once that calculation is done, I need to order the model by the resulting calculation. Is there a way to this in the model class where I create a temporary column on the fly and order by it?

Thanks, Robert

SomeModel.find :all, :select => "*, a + b + c as some_calculation", :order => 'some_calculation' (assuming you had columns a b c and were interested in their sum.

Fred

Thanks.

I actually got it to work by reordering the array after the fact. The calculations needed were too involved and required a lot of case switches to calculate so I wasn't able to do it on initial query.

This works for me: @SomeModel.sort! {|b,a| a.RankNumber <=> b.RankNumber }

It's definitely not as efficient as doing it during the initial query, but it works.

There's still a third option which is to precompute the rank (for example in before filters) and have it stored in the database. That way you can order by rank with straight SQL.

For example, the total of an invoice is computable from its parts, but having it cached in the database makes sorting invoice tables by total lighter.

Of course in your case this may not make sense, or it may not be worth the trouble depending on the details.