Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails PostgreSQL sort by integer value of string

I made a strategic mistake when developing database architecture on my Rails app

Now I have to implement sorting by price feature using

MyModel.order('price DESC')

price is a string type in the database, which cause 50 to be greater than 2000 for example

Are there any ways to implement such .order() without changing database structure?

EDIT:

I switched to correct type (integer) for price column. It took me an hour only to refactor.

like image 440
Sergey Khmelevskoy Avatar asked Oct 21 '16 15:10

Sergey Khmelevskoy


1 Answers

With PostgreSQL you will want to cast your string to integer/float/decimal (after you decide you 100% will not go and change the column type to correct one):

MyModel.order('price::integer DESC')

Consider this answer to make it work fast.

like image 126
Andrey Deineko Avatar answered Nov 15 '22 15:11

Andrey Deineko