I have a rails API which returns JSON to my React front end. I'm trying to sort by a calculated value for each item in a collection. I have a Space model which has an area attribute and a count attribute. I'd like to sort the response by total_area which is just area * count. I'm able to do this using sort_by but the process is pretty slow even with less than 100 records:
@spaces = Space.all
@spaces = @spaces.sort_by(&:total_area)
Where total_area is a Space class method:
def total_area
self.area * self.count
end
Is there anyway to do this within the database to get an improvement in speed? I've tried using the order method:
@spaces.order( "count * area" => :asc)
But I get the following postgres error:
PG::UndefinedColumn: ERROR: column spaces.count * area does not exist
Is is possible to do this in the database? Any suggestions on how I can, or how I could do this sort more quickly would be very much appreciated.