Rails: order by the sum of two columns

So, I have a Photo model that can be downloaded using full_size and presentation_size . When a user uploads a photo, I track it on the full_downloads and presentation_downloads object.

This is all good.

Sometimes I want to know how much has been downloaded. I have a simple total_downloads method that looks like this:

 def total_downloads self.full_downloads + self.presentation_downloads end 

My question: I would like to be able to order photos for all three of them (full, presentation, general download). The first two are easy, but how do you place an order for the sum of two columns? Note that this must be both SQLite and PG compatible at a minimum.

A side question: would it be faster to make the total_downloads method a request, and if so, what is the best way to write this? I know to summarize a class that you can call Photo.sum(...) , but I'm not sure how to do this for two columns on the same record.

Thanks!

+6
source share
2 answers

You can try the following:

 Photo.order('full_downloads + presentation_downloads') 

It will run this SQL query:

 SELECT "photos".* FROM "photos" ORDER BY full_downloads + presentation_downloads 

This is potentially slow. If you have a large data set and this sort order is often used, you should consider creating a column total_downloads and recalculating its value if the column for the full_downloads or presentation_downloads record changes.

+16
source

Photo.order('full_downloads + presentation_downloads DESC')

This will definitely be much faster than doing sorting in Ruby.

+3
source

Source: https://habr.com/ru/post/895385/


All Articles